层级访问

gjson支持对数据内容进行层级检索访问,层级分隔符号默认为”.“。该特性使得开发者可以灵活访问未知的数据结构内容变得非常简便。

示例1,基本使用

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

可以看到,gjson.Json对象可以通过非常灵活的层级筛选功能(j.GetFloat32("users.list.1.score"))检索到对应的变量信息。

示例2,自定义层级分隔符号

  1. data :=
  2. `{
  3. "users" : {
  4. "count" : 2,
  5. "list" : [
  6. {"name" : "Ming", "score" : 60},
  7. {"name" : "John", "score" : 99.5}
  8. ]
  9. }
  10. }`
  11. if j, err := gjson.DecodeToJson(data); err != nil {
  12. panic(err)
  13. } else {
  14. j.SetSplitChar('#')
  15. fmt.Println("John Score:", j.GetFloat32("users#list#1#score"))
  16. }
  17. // Output:
  18. // John Score: 99.5

可以看到,我们可以通过SetSplitChar方法设置我们自定义的分隔符号。

示例3,处理键名本身带有层级符号”.“的情况

  1. data :=
  2. `{
  3. "users" : {
  4. "count" : 100
  5. },
  6. "users.count" : 101
  7. }`
  8. if j, err := gjson.DecodeToJson(data); err != nil {
  9. glog.Error(err)
  10. } else {
  11. j.SetViolenceCheck(true)
  12. fmt.Println("Users Count:", j.GetInt("users.count"))
  13. }

运行之后打印出的结果为101。当键名存在”.“号时,我们可以通过SetViolenceCheck设置冲突检测,随后检索优先级将会按照:键名->层级,便并不会引起歧义。但是当冲突检测开关开启时,检索效率将会变低,默认为关闭状态。

注意事项

大家都知道,在Golang里面,map/slice类型其实是一个”引用类型”(也叫”指针类型”),因此当你对这种类型的变量 键值对/索引项 进行修改时,会同时修改到其对应的底层数据。

从效率上考虑,gjson包某些获取方法返回的数据类型为map/slice时,没有对齐做值拷贝,因此当你对返回的数据进行修改时,会同时修改gjson对应的底层数据。

例如:

  1. jsonContent := `{"map":{"key":"value"}, "slice":[59,90]}`
  2. j, _ := gjson.LoadJson(jsonContent)
  3. m := j.GetMap("map")
  4. fmt.Println(m)
  5. // Change the key-value pair.
  6. m["key"] = "john"
  7. // It changes the underlying key-value pair.
  8. fmt.Println(j.GetMap("map"))
  9. s := j.GetArray("slice")
  10. fmt.Println(s)
  11. // Change the value of specified index.
  12. s[0] = 100
  13. // It changes the underlying slice.
  14. fmt.Println(j.GetArray("slice"))
  15. // output:
  16. // map[key:value]
  17. // map[key:john]
  18. // [59 90]
  19. // [100 90]