gjson
GJSONGojson
SJSON jsonJJ
GJSONGJSON
github 的地址在这里。
安装
gjsongo
go install github.com/tidwall/gjson@latest
在文件的目录下执行:
$ go get -u github.com/tidwall/gjson
gjson
使用
获取相应的数值。
json
package main import "github.com/tidwall/gjson" const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}` func main() { value := gjson.Get(json, "name.last") println(value.String()) }
这将打印:
Prichard
jsongjsonjson
路径语法
路径是由点分隔的一系列键。密钥可能包含特殊的通配符“*”和“?”。要访问数组值,请使用索引作为键。要获取数组中的元素数量或访问子路径,请使用“#”字符。点和通配符可以用“\”转义。
{ "name": {"first": "Tom", "last": "Anderson"}, "age":37, "children": ["Sara","Alex","Jack"], "fav.movie": "Deer Hunter", "friends": [ {"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]}, {"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]}, {"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]} ] }
"name.last" >> "Anderson"
"age" >> 37
"children" >> ["Sara","Alex","Jack"]
"children.#" >> 3
"children.1" >> "Alex"
"child*.2" >> "Jack"
"c?ildren.0" >> "Sara"
"fav\.movie" >> "Deer Hunter"
"friends.#.first" >> ["Dale","Roger","Jane"]
"friends.1.last" >> "Craig"
您还可以使用 查询数组中的第一个匹配项#(…),或使用 查找所有匹配项#(…)#。查询支持==, !=, <, <=, >,>= 比较运算符和简单的模式匹配%(like) 和!% (not like) 运算符。
friends.#(last=="Murphy").first >> "Dale"
friends.#(last=="Murphy")#.first >> ["Dale","Jane"]
friends.#(age>45)#.last >> ["Craig","Murphy"]
friends.#(first%"D*").last >> "Murphy"
friends.#(first!%"D*").last >> "Craig"
friends.#(nets.#(=="fb"))#.first >> ["Dale","Roger"]
这样我们查找起来就非常方便了。