Python json模块与jsonpath模块区别详解
JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写。同时也方便了机器进行解析和生成。适用于进行数据交互的场景,比如网站前台与后台之间的数据交互。
JSON和XML相比较可谓不相上下。
Python3.X中自带了JSON模块,直接importjson就可以使用了。
官方文档:http://docs.python.org/library/json.html
Json在线解析网站:http://www.json.cn/
JSON
json简单来说就是JavaScript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构。
对象:对象在js中表示为{}括起来的内容,数据结构为{key1:value1,key2:value2,...}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为对象.key获取属性值,这个属性值的类型可以是数字、字符串、数组、对象。
数组:数组在js中是[]括起来的内容,数据结构为['Python',‘JavaScript','C++',...],取值方式和所有语言一样,使用索引获取,字段值的类型可以是数字、字符串、数组、对象。
json模块
json模块提供了四个功能:dumps、dump、loads、load,用于字符串和Python数据类型间进行转换。
1.json.dumps()
实现Python类型转化为Json字符串,返回一个str对象,从Python到Json的类型转换对照如下:
Python
Json
dict
object
list,tuple
array
str,utf-8
string
int,float
number
True
true
False
false
None
null
#!/usr/bin/python3 #-*-coding:utf-8-*- __author__='mayi' importjson listStr=[1,2,3,4] tupleStr=(1,2,3,4) dictStr={"city":"北京","name":"蚂蚁"} print(json.dumps(listStr)) #[1,2,3,4] print(type(json.dumps(listStr))) #print(json.dumps(tupleStr)) #[1,2,3,4] print(type(json.dumps(tupleStr))) # #注意:json.dumps()序列化时默认使用的ascii编码 #添加参数ensure_ascii=False禁用ascii编码,按utf-8编码 print(json.dumps(dictStr,ensure_ascii=False)) #{"city":"北京","name":"蚂蚁"} print(type(json.dumps(dictStr,ensure_ascii=False))) #
2.json.dump()
将Python内置类型序列化为Json对象后写入文件
#!/usr/bin/python3 #-*-coding:utf-8-*- __author__='mayi' importjson listStr=[{"city":"北京"},{"name":"蚂蚁"}] json.dump(listStr,open("listStr.json","w",encoding="utf-8"),ensure_ascii=False) dictStr={"city":"北京","name":"蚂蚁"} json.dump(dictStr,open("dictStr.json","w",encoding="utf-8"),ensure_ascii=False)
3.json.loads()
把Json格式字符串解码转换成Python对象,从Json到Python的类型转换对照如下:
Json
Python
object
dict
array
list
string
utf-8
number(int)
int
number(real)
float
true
True
false
False
null
None
#!/usr/bin/python3 #-*-coding:utf-8-*- __author__='mayi' importjson strList='[1,2,3,4]' strDict='{"city":"北京","name":"蚂蚁"}' print(json.loads(strList)) #[1,2,3,4] #json数据自动按utf-8存储 print(json.loads(strDict)) #{'city':'北京','name':'蚂蚁'}
4.json.load()
读取文件中Json形式的字符串,转换成Python类型
#!/usr/bin/python3 #-*-coding:utf-8-*- __author__='mayi' importjson strList=json.load(open("listStr.json","r",encoding="utf-8")) print(strList) #[{'city':'北京'},{'name':'蚂蚁'}] strDict=json.load(open("dictStr.json","r",encoding="utf-8")) print(strDict) #{'city':'北京','name':'蚂蚁'}
JsonPath
JsonPath是一种信息抽取类库,是从JSON文档中抽取指定信息的工具,提供多种语言实现版本,包括:JavaScript、Python、PHP和Java。
JsonPath对于JSON来说,相当于XPATH对于XML。
下载地址:https://pypi.python.org/pypi/jsonpath
安装方法:下载后解压之后执行pythonsetup.pyinstall
官方文档:http://goessner.net/articles/JsonPath
JsonPath与XPath语法对比:
JsonPath结构清晰,可读性高,复杂度低,非常容易匹配,下表中对应了XPath的用法。
Xpath
JSONPath
描述
/
$
根节点
.
@
现行节点
/
.or[]
取子节点
..
n/a
取父节点,Jsonpath未支持
//
..
不管位置,选择所有符合条件的节点
*
*
匹配所有元素节点
@
n/a
根据属性访问,JsonPath不支持
[]
[]
迭代器(可以在里边做简单的迭代操作,如数组下标,根据内容选值等)
|
[,]
支持迭代器中做多选
[]
?()
支持过滤操作
n/a
()
支持表达式计算
()
n/a
分组,JsonPath不支持
示例:
以拉勾网城市JSON文件:http://www.lagou.com/lbs/getAllCitySearchLabels.json为例,获取所有的城市名称。
#!/usr/bin/python3 #-*-coding:utf-8-*- __author__='mayi' importurllib.request importjson importjsonpath #拉勾网城市JSON文件 url='http://www.lagou.com/lbs/getAllCitySearchLabels.json' #User-Agent头 header={'User-Agent':'Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/39.0.2171.71Safari/537.36'} #url连同headers,一起构造Request请求,这个请求将附带chrome浏览器的User-Agent request=urllib.request.Request(url,headers=header) #向服务器发送这个请求 response=urllib.request.urlopen(request) #获取页面内容:bytes html=response.read() #转码:bytes转str html=html.decode("utf-8") #把json格式字符串转换成python对象 obj=json.loads(html) #从根节点开始,匹配name节点 city_list=jsonpath.jsonpath(obj,'$..name') #打印获取的name节点 print(city_list) #打印其类型 print(type(city_list)) #写入本地磁盘文件 withopen("city.json","w",encoding="utf-8")asf: content=json.dumps(city_list,ensure_ascii=False) f.write(content)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。