gjson
can not only flexibly parse and retrieve unknown data structure content but also dynamically create and modify data structure content.
Dynamic Creation
Example 1, Simple Usage
func main() {
j := gjson.New(nil)
j.Set("name", "John")
j.Set("score", 99.5)
fmt.Printf(
"Name: %s, Score: %v\n",
j.Get("name").String(),
j.Get("score").Float32(),
)
fmt.Println(j.MustToJsonString())
// Output:
// Name: John, Score: 99.5
// {"name":"John","score":99.5}
}
Example 2, Creating Arrays
func main() {
j := gjson.New(nil)
for i := 0; i < 5; i++ {
j.Set(fmt.Sprintf(`%d.id`, i), i)
j.Set(fmt.Sprintf(`%d.name`, i), fmt.Sprintf(`student-%d`, i))
}
fmt.Println(j.MustToJsonString())
// Output:
// [{"id":0,"name":"student-0"},{"id":1,"name":"student-1"},{"id":2,"name":"student-2"},{"id":3,"name":"student-3"},{"id":4,"name":"student-4"}]
}
Dynamic Modification
func main() {
data :=
`{
"users" : {
"count" : 2,
"list" : [
{"name" : "Ming", "score" : 60},
{"name" : "John", "score" : 59}
]
}
}`
if j, err := gjson.DecodeToJson(data); err != nil {
panic(err)
} else {
j.Set("users.list.1.score", 100)
fmt.Println("John Score:", j.Get("users.list.1.score").Float32())
fmt.Println(j.MustToJsonString())
}
// Output:
// John Score: 100
// {"users":{"count":2,"list":[{"name":"Ming","score":60},{"name":"John","score":100}]}}
}
JSON
data can be read through gjson
, and the internal variables can be changed using the Set
method. Of course, you can also add/delete
content. When you need to delete content, just set the value to nil
. The runtime modification features of the gjson
package are very powerful, and with the support of this feature, the encoding/decoding of various data structures becomes extremely flexible and convenient.