GoFrame gjson-对象创建

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 theres 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

作者:冒牌SEO,如若转载,请注明出处:https://www.web176.com/goframe/20897.html

(0)
打赏 支付宝 支付宝 微信 微信
冒牌SEO冒牌SEO
上一篇 2023年5月18日
下一篇 2023年5月18日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注