}
对上面的json数据进行处理,代码如下所示:
1 import json
3 import jsonpath as jsonpath
5 strData = '{"store":{"book":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"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}}}'
6 jsonData = json.loads(strData)
8 #绝对路径
9 checkUrl = "$.store.bicycle.color"
10 result = jsonpath.jsonpath(jsonData,checkUrl)
11 print(result)
13 #相对路径
14 checkUrl2 = "$..price"
15 result2 = jsonpath.jsonpath(jsonData,checkUrl2)
16 print(result2)
18 #只想拿某个路径下所有的某个元素的值
19 checkUrl3 = "$.store.book[*].price"
20 result3 = jsonpath.jsonpath(jsonData,checkUrl3)
21 print(result3)
23 #输出book节点中category为fiction的所有对象
24 checkUrl4 = "$.store.book[?(@.category=='fiction')]"
25 result4 = jsonpath.jsonpath(jsonData,checkUrl4)
26 print(result4)
28 #输出book节点中所有价格小于10的对象
29 checkUrl5 = "$.store.book[?(@.price<10)]"
30 result5 = jsonpath.jsonpath(jsonData,checkUrl5)
31 print(result5)
33 >>> 运行结果如下:
34 >>> ['red']
35 >>> [8.95, 22.99, 19.95]
36 >>> [8.95, 22.99]
37 >>> [{'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8', 'price': 22.99}]
38 >>> [{'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8.95}]
上面第一个是获取颜色,知道路径,所以直接用了绝对路径:$.store.bicycle.color
上面第二个是获取价格,里面有很多价格,不好确定路径,所以用了相对路径:$..price
后面所有都是有条件判断的,采用正则表达式的方式来获取满足条件的数据,所以采用了:$.store.book[条件].xx