somebodyoneday 2019-12-27
jsonpath | 描述 |
---|---|
$ | 根元素 |
@ | 当前对象元素 |
. | 子元素 |
.. | 递归下降(所有元素) |
* | 通配符 |
pip install jsonpath
json_data = { "code": 0, "message": "0", "ttl": 1, "data": { "isLogin": True, "email_verified": 0, "face": "http://i1.hdslb.com/bfs/face/17061e541785832b44426c51429ddfee39.jpg", "level_info": { "current_level": 0, "current_min": 0, "current_exp": 0, "next_exp": 1 }, "mid": 377206, "mobile_verified": 1, "money": 0, "moral": 70, "official": { "role": 0, "title": "", "desc": "", "type": -1 }, "officialVerify": { "type": -1, "desc": "" }, "pendant": { "pid": 0, "name": "", "image": "", "expire": 0 }, "scores": 0, "uname": "洒脱喽", "vipDueDate": 0, "vipStatus": 0, "vipType": 0, "vip_pay_type": 0, "vip_theme_type": 0, "wallet": { "mid": 377206, "bcoin_balance": 0, "coupon_balance": 0, "coupon_due_time": 0 }, "has_shop": False, "shop_url": "", "allowance_count": 0, "answer_status": 1 } }
import jsonpath
datas = json_data["data"] for data in datas.items(): print(data)
# 返回的是一个数组 datas = jsonpath.jsonpath(json_data, "$.data") for data in datas[0].items(): print(data)
# 普通取值需要先看json数据,找到uname节点,如果没有就会报错 data1 = json_data["data"]["uname"] print(data1) # jsonpath取值不需要看json数据,直接通过..(..就表示全局检索后面跟的属性)全局搜索uname属性,如果没有返回FALSE data2 = jsonpath.jsonpath(json_data, "$..uname") print(data2)
datas = jsonpath.jsonpath(json_data, "$..mid")
import json
data = {"name": "ming", "id": 18, "msg": None} json_data = '{"name":"Tom","id":19,"msg":null}'
res = json.loads(json_data) print(res, type(res))
res = json.dumps(data) print(res, type(res))
【完】