W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
?gjson
?支持對數(shù)據(jù)內(nèi)容進行層級檢索訪問,層級分隔符號默認為”?.
?“。該特性使得開發(fā)者可以靈活訪問未知的數(shù)據(jù)結(jié)構(gòu)內(nèi)容變得非常簡便。
func main() {
data :=
`{
"users" : {
"count" : 2,
"list" : [
{"name" : "Ming", "score" : 60},
{"name" : "John", "score" : 99.5}
]
}
}`
if j, err := gjson.DecodeToJson(data); err != nil {
panic(err)
} else {
fmt.Println("John Score:", j.Get("users.list.1.score"))
}
// Output:
// John Score: 99.5
}
可以看到,?gjson.Json
?對象可以通過非常靈活的層級篩選功能(?j.GetFloat32("users.list.1.score")
?)檢索到對應(yīng)的變量信息。
func main() {
data :=
`{
"users" : {
"count" : 2,
"list" : [
{"name" : "Ming", "score" : 60},
{"name" : "John", "score" : 99.5}
]
}
}`
if j, err := gjson.DecodeToJson(data); err != nil {
panic(err)
} else {
j.SetSplitChar('#')
fmt.Println("John Score:", j.Get("users#list#1#score"))
}
// Output:
// John Score: 99.5
}
可以看到,我們可以通過?SetSplitChar
?方法設(shè)置我們自定義的分隔符號。
func main() {
data :=
`{
"users" : {
"count" : 100
},
"users.count" : 101
}`
if j, err := gjson.DecodeToJson(data); err != nil {
glog.Error(gctx.New(), err)
} else {
j.SetViolenceCheck(true)
fmt.Println("Users Count:", j.Get("users.count"))
}
// Output:
// Users Count: 101
}
運行之后打印出的結(jié)果為?101
?。當鍵名存在”?.
?“號時,我們可以通過?SetViolenceCheck
?設(shè)置沖突檢測,隨后檢索優(yōu)先級將會按照:鍵名->層級,便并不會引起歧義。但是當沖突檢測開關(guān)開啟時,檢索效率將會變低,默認為關(guān)閉狀態(tài)。
大家都知道,在Golang里面,?map/slice
?類型其實是一個”引用類型”(也叫”指針類型”),因此當你對這種類型的變量 鍵值對/索引項 進行修改時,會同時修改到其對應(yīng)的底層數(shù)據(jù)。
從效率上考慮,?gjson
?包某些獲取方法返回的數(shù)據(jù)類型為?map/slice
?時,沒有對齊做值拷貝,因此當你對返回的數(shù)據(jù)進行修改時,會同時修改?gjson
?對應(yīng)的底層數(shù)據(jù)。
例如:
func main() {
jsonContent := `{"map":{"key":"value"}, "slice":[59,90]}`
j, _ := gjson.LoadJson(jsonContent)
m := j.Get("map")
mMap := m.Map()
fmt.Println(mMap)
// Change the key-value pair.
mMap["key"] = "john"
// It changes the underlying key-value pair.
fmt.Println(j.Get("map").Map())
s := j.Get("slice")
sArray := s.Array()
fmt.Println(sArray)
// Change the value of specified index.
sArray[0] = 100
// It changes the underlying slice.
fmt.Println(j.Get("slice").Array())
// output:
// map[key:value]
// map[key:john]
// [59 90]
// [100 90]
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: