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
jsonContent := `{"name":"john", "score":"100"}`
j := gjson.New(jsonContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
Creating from XML Data
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
Creating from a Struct Object
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
Custom Struct Conversion Tags
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
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
JSONFile
jsonFilePath := gtest.DataPath("json", "data1.json")
j, _ := gjson.Load(jsonFilePath)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
XMLFile
jsonFilePath := gtest.DataPath("xml", "data1.xml")
j, _ := gjson.Load(jsonFilePath)
fmt.Println(j.Get("doc.name"))
fmt.Println(j.Get("doc.score"))
Creating with LoadContent
jsonContent := `{"name":"john", "score":"100"}`
j, _ := gjson.LoadContent(jsonContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100