1.json格式处理jsonpath
https://www.cnblogs.com/aoyihuashao/p/8665873.html
dic = {
"error_code":0,
"stu_info": [
{
"id":2057,
"name":"xiaohei",
"sex":"nan",
"age":29,
"addr":"beijing",
"grade":"tianxie",
"phone":"18712321234",
"gold": {"id":2057,
"name":"xiaohei",
"sex":"nan"
}
},
{
"id":2057,
"name":"huxt",
"sex":"nan",
"age":29,
"addr":"beijing",
"grade":"tianxie",
"phone":"18712321234",
"gold":100
}
]
}
程序代码:
s = jsonpath.jsonpath(dic, '$..name') # 不管有多少层,写两个.都能取到
print(s)# ['xiaohei'] 返回的是一个列表
s = jsonpath.jsonpath(dic, '$..hehe') # 当不存在hehe这个key时,返回false
print(s)# False
运行结果:
['xiaohei', 'xiaohei', 'huxt']
False
2.操作符
jsonpath操作符3. 函数
可以在JsonPath表达式执行后进行调用,其输入值为表达式的结果。
4. 过滤器
过滤器是用于过滤数组的逻辑表达式,一个通常的表达式形如:[?(@.age > 18)],可以通过逻辑表达式&&或||组合多个过滤器表达式,例如[?(@.price < 10 && @.category == ‘fiction’)],字符串必须用单引号或双引号包围,例如[?(@.color == ‘blue’)] or [?(@.color == “blue”)]。
示例如下:
{
"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
}
代码
print(jsonpath.jsonpath(jsonpathStr,"$.store.book[0].author"))
print(jsonpath.jsonpath(jsonpathStr,"$.store.book[*].author"))
获取节点具体的值
$.store.* 显示所有叶子节点值
$.store..price获取所有具体节点值
$..book[0,1] 或 $..book[:2]获取具体节点数据
前2本 后2本
网友评论