动态创建

  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"}]

动态修改

动态创建

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

动态修改

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