一個很好用的Golang Json庫
來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。# 庫名 [ourjson](https://github.com/W1llyu/ourjson)https://github.com/W1llyu/ourjson## 官方的做法官方的做法主要是一整個json放一起解析,需要提前定義好struct來承載或者用一個map[string]interface來承載,擷取value時轉成相應的類型。但是在一些多層嵌套的json情境下,需要提前定義n個不需要的結構體去獲得子json對象的某個值,就比較麻煩。ourjson這個庫有點類似java裡面的JSONObject,下面是例子## 例子```gopackage mainimport ( "fmt" "github.com/W1llyu/ourjson")func main() {defer func() {if err := recover(); err != nil {fmt.Println(err)}}()jsonStr := `{"user": {"name": "aa","age": 10,"phone": "12222222222","emails": ["aa@164.com","aa@165.com"],"address": [{"number": "101","now_live": true},{"number": "102","now_live": null}],"account": {"balance": 999.9}}}`jsonObject, err := ourjson.ParseObject(jsonStr)fmt.Println(jsonObject, err)user := jsonObject.GetJsonObject("user")fmt.Println(user)name, err := user.GetString("name")fmt.Println(name, err)phone, err := user.GetInt64("phone")fmt.Println(phone, err)age, err := user.GetInt64("age")fmt.Println(age, err)account := user.GetJsonObject("account")fmt.Println(account)balance, err := account.GetFloat64("balance")fmt.Println(balance, err)email1, err := user.GetJsonArray("emails").GetString(0)fmt.Println(email1, err)address := user.GetJsonArray("address")fmt.Println(address)address1nowLive, err := user.GetJsonArray("address").GetJsonObject(0).GetBoolean("now_live")fmt.Println(address1nowLive, err)address2, err := address.Get(1)fmt.Println(address2, err)address2NowLive, err := address2.JsonObject().GetNullBoolean("now_live")fmt.Println(address2NowLive, err)}```361 次點擊