要开始使用 GJSON,请安装 Go 并运行go get:
$ go get -u github.com/tidwall/gjson
这将检索库。
获取一个值
Get 在 json 中搜索指定路径。路径采用点语法,例如“name.last”或“age”。当找到该值时,它会立即返回。
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
还有用于一次获取多个值的GetMany函数,以及用于处理 JSON 字节切片的GetBytes 。
路径语法
下面是路径语法的快速概述,有关更完整的信息,请查看GJSON 语法。
路径是一系列由点分隔的键。键可以包含特殊通配符“*”和“?”。要访问数组值,请使用索引作为键。要获取数组中的元素数或访问子路径,请使用“#”字符。点和通配符可以用“\”转义。
{
"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 >>
参考阅读
发表评论