W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
?gjson
?模塊除了最基礎(chǔ)支持的?JSON
?數(shù)據(jù)格式創(chuàng)建?Json
?對象,還支持常用的數(shù)據(jù)格式內(nèi)容創(chuàng)建?Json
?對象。支持的數(shù)據(jù)格式為:?JSON
?, ?XML
?, ?INI
?, ?YAML
?, ?TOML
?。此外,也支持直接通過?struct
?對象創(chuàng)建?Json
?對象。
對象創(chuàng)建常用?New
?和?Load*
?方法,更多的方法請查看接口文檔:https://pkg.go.dev/github.com/gogf/gf/v2/encoding/gjson
jsonContent := `{"name":"john", "score":"100"}`
j := gjson.New(jsonContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
jsonContent := `<?xml version="1.0" encoding="UTF-8"?><doc><name>john</name><score>100</score></doc>`
j := gjson.New(jsonContent)
// Note that there's root node in the XML content.
fmt.Println(j.Get("doc.name"))
fmt.Println(j.Get("doc.score"))
// Output:
// john
// 100
type Me struct {
Name string `json:"name"`
Score int `json:"score"`
}
me := Me{
Name: "john",
Score: 100,
}
j := gjson.New(me)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
type Me struct {
Name string `tag:"name"`
Score int `tag:"score"`
Title string
}
me := Me{
Name: "john",
Score: 100,
Title: "engineer",
}
// The parameter <tags> specifies custom priority tags for struct conversion to map,
// multiple tags joined with char ','.
j := gjson.NewWithTag(me, "tag")
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
fmt.Println(j.Get("Title"))
// Output:
// john
// 100
// engineer
最常用的是?Load
?和?LoadContent
?方法,前者通過文件路徑讀取,后者通過給定內(nèi)容創(chuàng)建?Json
?對象。方法內(nèi)部會自動(dòng)識別數(shù)據(jù)格式,并自動(dòng)解析轉(zhuǎn)換為?Json
?對象。
JSON
?文件 jsonFilePath := gdebug.TestDataPath("json", "data1.json")
j, _ := gjson.Load(jsonFilePath)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
XML
?文件 jsonFilePath := gdebug.TestDataPath("json", "data1.xml")
j, _ := gjson.Load(jsonFilePath)
fmt.Println(j.Get("doc.name"))
fmt.Println(j.Get("doc.score"))
jsonContent := `{"name":"john", "score":"100"}`
j, _ := gjson.LoadContent(jsonContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: