jsonpath是用于解析json文件的强大工具,不同语言都有各自的实现
jsonpath的设计思想和正则表达式相似
- 首先构建一个【jsonpath表达式】,或者说pattern
- 使用该表达式在json object中匹配结果
jsonpath in python
python的jsonpath_rw
使用类似正则表达式的方式,构建一个jsonpath_expr,然后用该expr去匹配json object,返回匹配的对象
jsonpath in golang
github.com/oliveagle/jsonpath
也是类似的
以下例子来自readme
json data:
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
code
import (
"github.com/oliveagle/jsonpath"
"encoding/json"
)
var json_data interface{}
json.Unmarshal([]byte(data), &json_data)
// "$.expensive" is a jsonpath_expr
res, err := jsonpath.JsonPathLookup(json_data, "$.expensive")
//---or reuse lookup pattern---
// Compile returns a jsonpath_expr, which is looked up in target json object
pat, _ := jsonpath.Compile(`$.store.book[?(@.price < $.expensive)].price`)
res, err := pat.Lookup(json_data)
网友评论