A json string, if you want to get the data in it, you need to parse it out
1. Applicable to the case where the structure of the json data is known
Use json.Unmarshal to parse json data into a structure
According to the format definition of json string data
struct
, it is used to save the decoded value. Here we first define a structure that is the same as the data structure to be parsed, and thenjson.Unmarshal
decode it. If the json data is complex, the custom struct will be complicated.
package main
import (
"encoding/json"
"fmt"
)
var jsonstr = `{"province":{"value":"110000",
"label":"北京市"},
"city":{"value":"110100",
"label":"北京城区"},
"district":{"value":"110115",
"label":"大兴区"}
}`
type JsonData struct {
Province JsonData2 `json:"province"`
City JsonData2 `json:"city"`
District JsonData2 `json:"district"`
}
type JsonData2 struct {
Value string `json:"value"`
Label string `json:"label"`
}
// json解码
func JsonDecode() {
//json解码
jsondata := JsonData{}
_ = json.Unmarshal([]byte(jsonstr), &jsondata)
fmt.Println(jsondata.Province.Label)
fmt.Println(jsondata.City.Label)
fmt.Println(jsondata.District.Label)
}
2. Applicable to the case where the structure of json data is unknown
1. Use maps
package main
import (
"encoding/json"
"fmt"
)
var jsonStr = `{
"name": "A",
"sex": "男",
"address": [
{ "province": "河南省", "city": "郑州市", "district": "金水区", "detail": "XX街道" },
{ "province": "河南省", "city": "安阳市", "district": "北关区", "detail": "YY街道" }
]
}
`
func main() {
var user map[string]interface{}
err := json.Unmarshal([]byte(jsonStr), &user)
if err != nil {
panic("解析失败")
}
fmt.Printf("名字:%s\n", user["name"].(string))
fmt.Printf("性别:%s\n", user["sex"].(string))
for i, address := range user["address"].([]interface{}) {
addr := address.(map[string]interface{})
fmt.Printf("地址%d:%s,%s,%s %s\n", i, addr["province"].(string), addr["city"].(string), addr["district"].(string), addr["detail"].(string))
}
}
2. Use a tripartite package
1、github.com/bitly/go-simplejson
package main
import (
"fmt"
"github.com/bitly/go-simplejson"
)
var jsonStr := `{
"name": "A",
"sex": "男",
"address": [
{ "province": "河南省", "city": "郑州市", "district": "金水区", "detail": "XX街道" },
{ "province": "河南省", "city": "安阳市", "district": "北关区", "detail": "YY街道" }
]
}`
func main() {
// github.com/bitly/go-simplejson
jst, err := simplejson.NewJson(jsonStr)
if err != nil {
panic("解析失败")
}
name, _ := jst.Get("name").String()
sex, _ := jst.Get("sex").String()
fmt.Printf("名字:%s\n", name)
fmt.Printf("性别:%s\n", sex)
for i, v := range jst.Get("address").MustArray() {
ads := v // v等同于jst.Get("address").GetIndex(i)
province, _ := ads.Get("province").String()
city, _ := ads.Get("city").String()
district, _ := ads.Get("district").String()
detail, _ := ads.Get("detail").String()
fmt.Printf("地址%d:%s,%s,%s %s\n", i, province, city, district, detail)
}
}
2、github.com/spf13/viper
1. It is necessary to
viper.SetConfigType("json")函数
specify the format of the data to be parsed, otherwise even ifviper.ReadConfig
no error is reported, no result will be returned after parsing2. Methods
viper.Get(),viper.GetString(),viper.GetBool()
, etc. can easily obtain the key value, and at the same time, it can also judge the type of the key value very well
package main
import (
"fmt"
"strings"
"github.com/spf13/viper"
)
var jsonstr= `{
"name": "tian",
"flag": false,
"address": {
"city": "北京",
"area": "中国"
}
}`
func main() {
// 设置需要配置的数据类型为json
viper.SetConfigType("json")
// 读取数据到viper
if err := viper.ReadConfig(strings.NewReader(jsonstr)); err != nil {
fmt.Println(err)
}
fmt.Printf("数据的所有键值: %v\n", viper.AllKeys())
fmt.Printf("解析后的数据:%v\n", viper.AllSettings())
fmt.Printf("The name is %s and the area is %s\n", viper.Get("name"), viper.Get("address.area"))
}
3、github.com/thedevsaddam/gojsonq
After using Find to query the name, Reset()
the method is called once. Because gojsonqFind
will record the current point internally when calling the method, and the next query will start from the last recorded point
package main
import (
"fmt"
"github.com/thedevsaddam/gojsonq/v2"
)
var jsonstr = `{
"name": "sam",
"flag": true,
"address": {
"city": "北京",
"area": "中国"
}
}`
func main() {
jst:= gojsonq.New().FromString(jsonstr)
namestr := jst.Find("name").(string)
jst.Reset()
citystr := jst.Find("address.city")
fmt.Printf("The name is %s and the city is %v", namestr, citystr)
}