GoFrame gjson-對象創(chuàng)建

2022-04-12 09:30 更新

?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

使用New方法創(chuàng)建

通過JSON數(shù)據(jù)創(chuàng)建

jsonContent := `{"name":"john", "score":"100"}`
j := gjson.New(jsonContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100

通過XML數(shù)據(jù)創(chuàng)建

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

通過Strcut對象創(chuàng)建

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

自定義Struct轉(zhuǎn)換標(biāo)簽

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*方法創(chuàng)建

最常用的是?Load?和?LoadContent?方法,前者通過文件路徑讀取,后者通過給定內(nèi)容創(chuàng)建?Json?對象。方法內(nèi)部會自動(dòng)識別數(shù)據(jù)格式,并自動(dòng)解析轉(zhuǎn)換為?Json?對象。

通過Load方法創(chuàng)建

  • ?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"))

通過LoadContent創(chuàng)建

jsonContent := `{"name":"john", "score":"100"}`
j, _ := gjson.LoadContent(jsonContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號