前言
现在有一个json格式的字符串,应该怎么解析呢,这里总结了以下4种方法
1. json.Unmarshal
func json.Unmarshal(data []byte, v any) error
e.g.
structjson.Unmarshal
程序运行后的结果如下:
PS E:\goland-workspace\GolangLearning\Common\json数据处理\unmarshal> go run .\main.go
解码后的结果为:{tian false {beijing China}}
2. viper.ReadConfig
go get -u github.com/spf13/viper
func viper.ReadConfig(in io.Reader) error
e.g.
viper.SetConfigType("json")viper.ReadConfig
viper.Get(),viper.GetString(),viper.GetBool()
程序运行后的结果如下:
PS E:\goland-workspace\GolangLearning\Common\json数据处理\viper> go run .\main.go
数据的所有键值: [address.city address.country name married]
解析后的数据:map[address:map[city:beijing country:China] married:false name:tian]
the type of "married" is bool
The name is tian and the country is China
3. simplejson.NewJson
go get -u "github.com/bitly/go-simplejson"
e.g.
程序运行后的结果如下:
PS E:\goland-workspace\GolangLearning\Common\json数据处理\simpleJson> go run .\main.go
The name is tian and the city is beijing
4. gojsonq.New().FromString()
go get -u github.com/thedevsaddam/gojsonq
e.g.
Reset()Find
程序运行后的结果如下:
PS E:\goland-workspace\GolangLearning\Common\json数据处理\gojsonq> go run .\main.go
The name is tian and the city is beijing