golang解析json數(shù)據(jù)的4種方法總結(jié)
前言
現(xiàn)在有一個json格式的字符串,應(yīng)該怎么解析呢,這里總結(jié)了以下4種方法
1. json.Unmarshal
函數(shù)func json.Unmarshal(data []byte, v any) error就是用來解析json編碼的data,然后將結(jié)果保存在指針v指向的值里
e.g.
package main
import (
"encoding/json"
"fmt"
)
type user struct {
Name string
Married bool
Address struct {
City string
Country string
}
}
func main() {
user1 := `{
"name": "tian",
"married": false,
"address": {
"city": "beijing",
"country": "China"
}
}`
user1Struct := &user{}
json.Unmarshal([]byte(user1), user1Struct)
fmt.Printf("解碼后的結(jié)果為:%v", *user1Struct)
}
- 首先根據(jù)json數(shù)據(jù)的格式定義
struct,用來保存解碼后的值。這里首先定義了一個user結(jié)構(gòu)體,然后通過json.Unmarshal進行解碼 - 缺點很明顯,如果json數(shù)據(jù)很復(fù)雜,自定義的struct就跟著復(fù)雜。
程序運行后的結(jié)果如下:
PS E:\goland-workspace\GolangLearning\Common\json數(shù)據(jù)處理\unmarshal> go run .\main.go
解碼后的結(jié)果為:{tian false {beijing China}}
2. viper.ReadConfig
使用go get -u github.com/spf13/viper 進行下載
函數(shù)func viper.ReadConfig(in io.Reader) error用于從in中讀取數(shù)據(jù)并解析
e.g.
package main
import (
"fmt"
"strings"
"github.com/spf13/viper"
)
func main() {
user1 := `{
"name": "tian",
"married": false,
"address": {
"city": "beijing",
"country": "China"
}
}`
// 指定配置的類型為json
viper.SetConfigType("json")
// 讀取數(shù)據(jù)
if err := viper.ReadConfig(strings.NewReader(user1)); err != nil {
fmt.Println(err)
}
fmt.Printf("數(shù)據(jù)的所有鍵值: %v\n", viper.AllKeys())
fmt.Printf("解析后的數(shù)據(jù):%v\n", viper.AllSettings())
fmt.Printf("the type of \"married\" is %s\n", reflect.TypeOf(viper.Get("married")))
fmt.Printf("The name is %s and the country is %s\n", viper.Get("name"), viper.Get("address.country"))
}
首先要通過viper.SetConfigType("json")指定要解析數(shù)據(jù)的格式,否則即使viper.ReadConfig返回值沒有報錯,也得不到解析后的結(jié)果??梢圆榭?a rel="external nofollow" target="_blank">https://github.com/spf13/viper/issues/316
方法viper.Get(),viper.GetString(),viper.GetBool()等等可以方便獲取鍵值,同時對于鍵值的類型也能很好的判斷
程序運行后的結(jié)果如下:
PS E:\goland-workspace\GolangLearning\Common\json數(shù)據(jù)處理\viper> go run .\main.go
數(shù)據(jù)的所有鍵值: [address.city address.country name married]
解析后的數(shù)據(jù):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.
package main
import (
"fmt"
"github.com/bitly/go-simplejson"
)
func main() {
user1 := `{
"name": "tian",
"married": false,
"address": {
"city": "beijing",
"country": "China"
}
}`
user1json, err := simplejson.NewJson([]byte(user1))
if err != nil {
fmt.Println(err)
}
name1, _ := user1json.Get("name").String()
city1, _ := user1json.Get("address").Get("city").String()
fmt.Printf("The name is %s and the city is %s", name1, city1)
}
程序運行后的結(jié)果如下:
PS E:\goland-workspace\GolangLearning\Common\json數(shù)據(jù)處理\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.
package main
import (
"fmt"
"github.com/thedevsaddam/gojsonq/v2"
)
func main() {
user1 := `{
"name": "tian",
"married": false,
"address": {
"city": "beijing",
"country": "China"
}
}`
user1json := gojsonq.New().FromString(user1)
name1 := user1json.Find("name").(string)
user1json.Reset()
city1 := user1json.Find("address.city")
fmt.Printf("The name is %s and the city is %v", name1, city1)
}
在第一次查詢name之后,手動調(diào)用了一次Reset()方法。因為JSONQ對象在調(diào)用Find方法時,內(nèi)部會記錄當前的節(jié)點,下一個查詢會從上次查找的節(jié)點開始
程序運行后的結(jié)果如下:
PS E:\goland-workspace\GolangLearning\Common\json數(shù)據(jù)處理\gojsonq> go run .\main.go
The name is tian and the city is beijing
總結(jié)
到此這篇關(guān)于golang解析json數(shù)據(jù)的4種方法的文章就介紹到這了,更多相關(guān)golang解析json數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解如何使用Golang操作MongoDB數(shù)據(jù)庫
在現(xiàn)代開發(fā)中,數(shù)據(jù)存儲是一個至關(guān)重要的環(huán)節(jié),MongoDB作為一種NoSQL數(shù)據(jù)庫,提供了強大的功能和靈活的數(shù)據(jù)模型,與Golang的高性能和并發(fā)性能非常契合,本文將探討Golang與MongoDB的完美組合,介紹如何使用Golang操作MongoDB數(shù)據(jù)庫,需要的朋友可以參考下2023-11-11

