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

  1. func main() {
  2. j := gjson.New(nil)
  3. j.Set("name", "John")
  4. j.Set("score", 99.5)
  5. fmt.Printf(
  6. "Name: %s, Score: %v\n",
  7. j.Get("name").String(),
  8. j.Get("score").Float32(),
  9. )
  10. fmt.Println(j.MustToJsonString())
  11. // Output:
  12. // Name: John, Score: 99.5
  13. // {"name":"John","score":99.5}
  14. }

Example 2, Creating Arrays

  1. func main() {
  2. j := gjson.New(nil)
  3. for i := 0; i < 5; i++ {
  4. j.Set(fmt.Sprintf(`%d.id`, i), i)
  5. j.Set(fmt.Sprintf(`%d.name`, i), fmt.Sprintf(`student-%d`, i))
  6. }
  7. fmt.Println(j.MustToJsonString())
  8. // Output:
  9. // [{"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"}]
  10. }

Dynamic Modification

  1. func main() {
  2. data :=
  3. `{
  4. "users" : {
  5. "count" : 2,
  6. "list" : [
  7. {"name" : "Ming", "score" : 60},
  8. {"name" : "John", "score" : 59}
  9. ]
  10. }
  11. }`
  12. if j, err := gjson.DecodeToJson(data); err != nil {
  13. panic(err)
  14. } else {
  15. j.Set("users.list.1.score", 100)
  16. fmt.Println("John Score:", j.Get("users.list.1.score").Float32())
  17. fmt.Println(j.MustToJsonString())
  18. }
  19. // Output:
  20. // John Score: 100
  21. // {"users":{"count":2,"list":[{"name":"Ming","score":60},{"name":"John","score":100}]}}
  22. }

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.