GoFrame gjson-对象创建

2022-04-12 09:30 更新

gjson​模块除了最基础支持的​JSON​数据格式创建​Json​对象,还支持常用的数据格式内容创建​Json​对象。支持的数据格式为:​JSON​, ​XML​, ​INI​, ​YAML​, ​TOML​。此外,也支持直接通过​struct​对象创建​Json​对象。

对象创建常用​New​和​Load*​方法,更多的方法请查看接口文档:https://pkg.go.dev/github.com/gogf/gf/v2/encoding/gjson

使用New方法创建

通过JSON数据创建

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

通过XML数据创建

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对象创建

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转换标签

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*方法创建

最常用的是​Load​和​LoadContent​方法,前者通过文件路径读取,后者通过给定内容创建​Json​对象。方法内部会自动识别数据格式,并自动解析转换为​Json​对象。

通过Load方法创建

  • 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创建

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


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号