python如何快速获取层次比较深的json数据中的某个值

发布时间 2023-11-28 13:24:03作者: 秒秒开心

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

 

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

 1 {
 2     "store": {
 3         "book": [
 4             {
 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     }
23 }

对上面的json数据进行处理,代码如下所示:

 1 import json  
 2   
 3 import jsonpath as jsonpath  
 4   
 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)  
 7   
 8 #绝对路径  
 9 checkUrl = "$.store.bicycle.color"  
10 result = jsonpath.jsonpath(jsonData,checkUrl)  
11 print(result)  
12   
13 #相对路径  
14 checkUrl2 = "$..price"  
15 result2 = jsonpath.jsonpath(jsonData,checkUrl2)  
16 print(result2)  
17   
18 #只想拿某个路径下所有的某个元素的值  
19 checkUrl3 = "$.store.book[*].price"  
20 result3 = jsonpath.jsonpath(jsonData,checkUrl3)  
21 print(result3)  
22   
23 #输出book节点中category为fiction的所有对象  
24 checkUrl4 = "$.store.book[?(@.category=='fiction')]"  
25 result4 = jsonpath.jsonpath(jsonData,checkUrl4)  
26 print(result4)  
27   
28 #输出book节点中所有价格小于10的对象  
29 checkUrl5 = "$.store.book[?(@.price<10)]"  
30 result5 = jsonpath.jsonpath(jsonData,checkUrl5)  
31 print(result5)
32 
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