相关文章推荐
憨厚的黄瓜  ·  高雄市立仁武高級中學·  4 月前    · 
贪玩的手套  ·  文档(PDF Word Excel ...·  4 月前    · 
果断的围巾  ·  checkbox wpf ...·  1 年前    · 

一、问题:
如何快速获取层次比较深的json数据中的某个值?

二、回答
用jsonpath即可:
如果知道路径则采用$.xx.xx绝对路径的方式获取
如果不知道路径则采用$..xx相对路径的方式获取
如果需要符号某个条件获取则采用$.xx.xx[条件]获取

2 " store " : { 3 " book " : [ 5 " category " : " reference " , 6 " author " : " Nigel Rees " , 7 " title " : " Sayings of the Century " , 8 " price " : 8.95 9 }, 10 { 11 " category " : " fiction " , 12 " author " : " J. R. R. Tolkien " , 13 " title " : " The Lord of the Rings " , 14 " isbn " : " 0-395-19395-8 " , 15 " price " : 22.99 16 } 17 ], 18 " bicycle " : { 19 " color " : " red " , 20 " price " : 19.95 21 } 22 }

对上面的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