The gjson module not only supports creating Json objects from the basic JSON data format but also supports creating Json objects from common data formats. Supported data formats include: JSON, XML, INI, YAML, TOML, PROPERTIES. Additionally, it also supports creating Json objects directly from struct objects.

The commonly used methods for object creation are New and Load*. For more methods, please refer to the interface documentation: https://pkg.go.dev/github.com/gogf/gf/v2/encoding/gjson

Creating with the New Method

Creating from JSON Data

  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

Creating from XML Data

  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

Creating from a Struct Object

  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

Custom Struct Conversion Tags

  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

Creating with the Load* Method

The most commonly used methods are Load and LoadContent, the former reads from a file path, and the latter creates a Json object from given content. The methods automatically recognize the data format internally, and automatically parse and convert them to Json objects.

Creating with the Load Method

  1. JSON File
  1. jsonFilePath := gtest.DataPath("json", "data1.json")
  2. j, _ := gjson.Load(jsonFilePath)
  3. fmt.Println(j.Get("name"))
  4. fmt.Println(j.Get("score"))
  1. XML File
  1. jsonFilePath := gtest.DataPath("xml", "data1.xml")
  2. j, _ := gjson.Load(jsonFilePath)
  3. fmt.Println(j.Get("doc.name"))
  4. fmt.Println(j.Get("doc.score"))

Creating with 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