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

对象创建常用NewLoad*方法,更多的方法请查看接口文档:https://godoc.org/github.com/gogf/gf/encoding/gjson

使用New方法创建

通过JSON数据创建

  1. jsonContent := `{"name":"john", "score":"100"}`
  2. j := gjson.New(jsonContent)
  3. fmt.Println(j.Get("name"))
  4. fmt.Println(j.Get("score"))
  5. // Output:
  6. // john
  7. // 100

通过XML数据创建

  1. jsonContent := `<?xml version="1.0" encoding="UTF-8"?><doc><name>john</name><score>100</score></doc>`
  2. j := gjson.New(jsonContent)
  3. // Note that there's root node in the XML content.
  4. fmt.Println(j.Get("doc.name"))
  5. fmt.Println(j.Get("doc.score"))
  6. // Output:
  7. // john
  8. // 100

通过Strcut对象创建

  1. type Me struct {
  2. Name string `json:"name"`
  3. Score int `json:"score"`
  4. }
  5. me := Me{
  6. Name: "john",
  7. Score: 100,
  8. }
  9. j := gjson.New(me)
  10. fmt.Println(j.Get("name"))
  11. fmt.Println(j.Get("score"))
  12. // Output:
  13. // john
  14. // 100

自定义Struct转换标签

  1. type Me struct {
  2. Name string `tag:"name"`
  3. Score int `tag:"score"`
  4. Title string
  5. }
  6. me := Me{
  7. Name: "john",
  8. Score: 100,
  9. Title: "engineer",
  10. }
  11. // The parameter <tags> specifies custom priority tags for struct conversion to map,
  12. // multiple tags joined with char ','.
  13. j := gjson.NewWithTag(me, "tag")
  14. fmt.Println(j.Get("name"))
  15. fmt.Println(j.Get("score"))
  16. fmt.Println(j.Get("Title"))
  17. // Output:
  18. // john
  19. // 100
  20. // engineer

使用Load*方法创建

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

通过Load方法创建

  1. JSON文件

    1. jsonFilePath := gdebug.TestDataPath("json", "data1.json")
    2. j, _ := gjson.Load(jsonFilePath)
    3. fmt.Println(j.Get("name"))
    4. fmt.Println(j.Get("score"))
  2. XML文件

    1. jsonFilePath := gdebug.TestDataPath("json", "data1.xml")
    2. j, _ := gjson.Load(jsonFilePath)
    3. fmt.Println(j.Get("doc.name"))
    4. fmt.Println(j.Get("doc.score"))

通过LoadContent创建

  1. jsonContent := `{"name":"john", "score":"100"}`
  2. j, _ := gjson.LoadContent(jsonContent)
  3. fmt.Println(j.Get("name"))
  4. fmt.Println(j.Get("score"))
  5. // Output:
  6. // john
  7. // 100

Content Menu