[600]python之jsonpath

json

官方文档:http://docs.python.org/library/json.html

Json在线解析网站:http://www.json.cn/#

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写。同时也方便了机器进行解析和生成。适用于进行数据交互的场景,比如网站前台与后台之间的数据交互。

1.1、json.loads()

把Json格式字符串解码转换成Python对象,从json到python的类型转化对照如下:

JSONPython
objectdict
arraylist
stringstr
number (int)int
number (real)float
trueTrue
falseFalse
nullNone
import json

strList = '[1, 2, 3, 4]'
strDict = '{"city": "北京", "name": "大猫"}'

print(json.loads(strList))
print(json.loads(strDict))
'''
输出结果:
[1, 2, 3, 4]
{"city": "北京", "name": "大猫"}
'''

1.2、json.dumps()

实现python类型转化为json字符串,返回一个str对象把一个Python对象编码转换成Json字符串,从python原始类型向json类型的转化对照如下:

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int- & float-derived Enumsnumber
Truetrue
Falsefalse
Nonenull
import json

listStr = [1, 2, 3, 4]
tupleStr = (1, 2, 3, 4)
dictStr = {"city": "北京", "name": "大猫"}

print(json.dumps(listStr))
print(json.dumps(tupleStr))

# 注意:json.dumps() 序列化时默认使用的ascii编码
# 添加参数 ensure_ascii=False 禁用ascii编码,按utf-8编码
print(json.dumps(dictStr))
print(json.dumps(dictStr, ensure_ascii=False))

'''
输出结果:
[1, 2, 3, 4]
[1, 2, 3, 4]
{"city": "\u5317\u4eac", "name": "\u5927\u732b"}
{"city": "北京", "name": "大猫"}
'''

1.3、json.load()

读取文件中json形式的字符串元素 转化成python类型

import json

strList = json.load(open("listStr.json"))
print(strList)

strDict = json.load(open("dictStr.json"))
print(strDict)

1.4、json.dump()

将Python内置类型序列化为json对象后写入文件

import json

listStr = [{"city": "北京"}, {"name": "大刘"}]
json.dump(listStr, open("listStr.json","w"), ensure_ascii=False)

dictStr = {"city": "北京", "name": "大刘"}
json.dump(dictStr, open("dictStr.json","w"), ensure_ascii=False)

JsonPath

**官方文档:**http://goessner.net/articles/JsonPath
https://pypi.org/project/jsonpath/

JsonPath用符号$表示最外层对象,类似于Xpath中的根元素

JsonPath可以通过点语法来检索数据,如:shell $.store.book[0].title,也可以使用中括号[]的形式,如shell $['store']['book'][0]['title']

2.1、JsonPath与Xpath语法对比

Json结构清晰,可读性高,复杂度低,非常容易匹配,下表中对应了XPath的用法

XPathJSONPath描述
/$根节点
.@现行节点v
/.or[]取子节点
n/a取父节点,Jsonpath未支持
//就是不管位置,选择所有符合条件的条件
**匹配所有元素节点
@n/a根据属性访问,Json不支持,因为Json是个Key-value递归结构,不需要。
[][]迭代器标示(可以在里边做简单的迭代操作,如数组下标,根据内容选值等)
[,]支持迭代器中做多选。
[]?()支持过滤操作.
n/a()支持表达式计算
()n/a分组,JsonPath不支持
import jsonpath

jsonobj ={
    "state":1,
    "message":"success",
    "content":{
        "data":{
            "allCitySearchLabels":{
                "A":[{"id":105795,"name":"澳门特别行政区"},
                     {"id":671,"name":"安庆"},
                     {"id":601,"name":"鞍山"}
                     ]
                }
            }
        }
}
# 从根节点开始,匹配name节点
citylist = jsonpath.jsonpath(jsonobj,'$..name')

jsonpath-rw

官方文档:https://pypi.python.org/pypi/jsonpath-rw
https://github.com/kennknowles/python-jsonpath-rw

安装

pip install jsonpath-rw

用法

>>> from jsonpath_rw import jsonpath, parse
>>> json_obj = {"student":[{"male":176,"female":162},{"male":174,"female":159}]}
>>> jsonpath_expr = parse("student[*].male")
>>> male = jsonpath_expr.find(json_obj)
>>> male #返回的是list,但是不是我们想要的值
[DatumInContext(value=176, path=Fields('male'), context=DatumInContext(value={'male': 176, 'female': 162}, path=<jsonpath_rw.jsonpath.Index object at 0x000001C6B95109B0>, context=DatumInContext(value=[{'male': 176, 'female': 162}, {'male': 174, 'female': 159}], path=Fields('student'), context=DatumInContext(value={'student': [{'male': 176, 'female': 162}, {'male': 174, 'female': 159}]}, path=This(), context=None)))), DatumInContext(value=174, path=Fields('male'), context=DatumInContext(value={'male': 174, 'female': 159}, path=<jsonpath_rw.jsonpath.Index object at 0x000001C6B9510588>, context=DatumInContext(value=[{'male': 176, 'female': 162}, {'male': 174, 'female': 159}], path=Fields('student'), context=DatumInContext(value={'student': [{'male': 176, 'female': 162}, {'male': 174, 'female': 159}]}, path=This(), context=None))))]

#想要获取值,要用如下方法
>>> [match.value for match in male]
[176, 174]

------------------------------------------------------------------------------------
>>> jsonpath_expr = parse('foo[*].baz')
>>> from jsonpath_rw.jsonpath import Fields
>>> from jsonpath_rw.jsonpath import Slice
#jsonpath_expr_direct 等价于jsonpath_expr 
>>> jsonpath_expr_direct = Fields('foo').child(Slice('*')).child(Fields('baz'))

>>> [match.value for match in jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]})]
[1, 2]

>>> [str(match.full_path) for match in jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]})]
['foo.[0].baz', 'foo.[1].baz']

>>> [match.value for match in parse('a.*.b.`parent`.c').find({'a': {'x': {'b': 1, 'c': 'number one'}, 'y': {'b': 2, 'c': 'number two'}}})]
['number two', 'number one']


PS:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线JSON代码检验、检验、美化、格式化工具: http://tools.jb51.net/code/json

JSON在线格式化工具: http://tools.jb51.net/code/jsonformat

在线XML/JSON互相转换工具: http://tools.jb51.net/code/xmljson

json代码在线格式化/美化/压缩/编辑/转换工具: http://tools.jb51.net/code/jsoncodeformat

在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans

参考:https://www.cnblogs.com/wongbingming/p/6896886.html
https://blog.csdn.net/Ka_Ka314/article/details/81014589
https://www.jianshu.com/p/9721ddb9546e
https://www.jb51.net/article/144815.htm

  • 6
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小董

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值