jsonpath
jsonpath 用于多层嵌套 json格式的 解析。
pip install jsonpath
JsonPath
描述
$
根节点
@
现行节点
.or[]
取子节点
n/a
取父节点,jsonpath为支持
..
就是不管位置,选择所有复合条件的条件
*
匹配所有元素节点
n/a
根据属性访问,json不支持,因为json是个key-value递归结构,不需要数属性访问
[]
迭代器标示(可以在里边做简单的迭代操作,如数组下标,根据内容选值等)
[,]
支持迭代器中做多选
"htmlcode">
book_dict = { "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 } } }
JsonPath
Result
$.store.book[*].author
store中的所有的book作者
$…author
所有的作者
$.store.*
store下的所有元素
$.store…price
store中的所有价钱
$…book[2]
第三本书
$…book[(@.length-1)]
最后一本书
$…book[0,1]
取前两本书
$…book["htmlcode">
import jsonpath result = { "code": 0, "data": [ { "age": 20, "create_time": "2019-09-15", "id": 1, "mail": "283340479@qq.com", "name": "yoyo", "sex": "M" }, { "age": 21, "create_time": "2019-09-16", "id": 2, "mail": "123445@qq.com", "name": "yoyo111", "sex": "M" } ], "msg": "success!" } msg = jsonpath.jsonpath(result, '$.msg') print(msg) # 输出结果 ['success!'] names = jsonpath.jsonpath(result, '$..name') print(names) # 输出结果 ['yoyo', 'yoyo111'] no = jsonpath.jsonpath(result, '$..yoyo') print(no) # 找不到是结果是 False
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。