Python爬虫的json模块与jsonpath模块?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
json (JavaScript对象表示法)是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写。同时也方便了机器进行解析和生成。适用于进行数据交互的场景,比如网站前台与后台之间的数据交互. json和XML相比较可谓不相上下。
Python 3。X中自带了JSON模块,直接进口JSON就可以使用了。
官方文档:http://docs.python.org/library/json.html
JSON在线解析网站:http://www.json.cn/
<强> JSON 强>
JSON简单来说就是JavaScript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构。
对象:对象在js中表示为{}括起来的内容,数据结构为{key1: value1, key2: value2,…}的键值对的结构,在面向对象的语言中,主要为对象的属性,价值为对应的属性值,所以很容易理解,取值方法为对象。关键获取属性值,这个属性值的类型可以是数字,字符串,数组,对象。
数组:数组在js中是[]括起来的内容,数据结构为[& # 39;Python # 39;,“javascript # 39; & # 39; C + + & # 39;,…),取值方式和所有语言一样,使用索引获取,字段值的类型可以是数字,字符串,数组,对象。
<强> json模块强>
json模块提供了四个功能:转储,转储,负载,负载,用于字符串和Python数据类型间进行转换。
<强> 1. json.dumps() 强>
实现Python类型转化为json字符串,返回一个str对象,从Python到json的类型转换对照如下:
# !/usr/bin/python3 #,- *安康;编码:utf-8 - * , import json , 时间=listStr [1,, 2,, 3,, 4] tupleStr =, (1,, 2,, 3,, 4) dictStr =, {“city":,“北京“,,“name":,“蚂蚁“} , print (json.dumps (listStr)) #,(1,,2,,3,,4] , print(类型(json.dumps (listStr))) #,& lt; class & # 39; str # 39;比; , print (json.dumps (tupleStr)) #,(1,,2,,3,,4] , print(类型(json.dumps (tupleStr))) #,& lt; class & # 39; str # 39;比; , #,注意:json.dumps(),序列化时默认使用的ascii编码 #,添加参数,ensure_ascii=False 禁用ascii编码,按utf - 8编码 print (json.dumps (dictStr, ensure_ascii =, False)) #,{“city":,“北京“,,“name":,“蚂蚁“} , print(类型(json.dumps (dictStr, ensure_ascii =, False))) #,& lt; class & # 39; str # 39;在
<强> 2. json.dump() 强>
,将Python内置类型序列化为Json对象后写入文件
# !/usr/bin/python3 #,- *安康;编码:utf-8 - * , import json , 时间=listStr [{“city":,“北京“},,{“name":“蚂蚁“}] json.dump (listStr, open (“listStr.json",,“w",, encoding =,“utf-8"),, ensure_ascii =,假) , dictStr =, {“city":,“北京“,,“name":,“蚂蚁“} json.dump (dictStr, open (“dictStr.json",,“w",, encoding =,“utf-8"),, ensure_ascii =, False)
<强> 3. json.loads() 强>
把Json格式字符串解码转换成Python对象,从Json到Python的类型转换对照如下:
# !/usr/bin/python3 #,- *安康;编码:utf-8 - * 时间=__author__ & # 39;马邑村# 39; , import json , 时间=strList & # 39; [1,, 2,, 3,, 4] & # 39; , 时间=strDict & # 39; {“city":,“北京“,,“name":,“蚂蚁“}& # 39; , print (json.loads (strList)) #,(1,,2,,3,,4] , #,json数据自动按utf - 8存储 print (json.loads (strDict)) #,{& # 39;城市# 39;:,& # 39;北京& # 39;,,& # 39;名字# 39;:,& # 39;蚂蚁& # 39;}
<强> 4. json.load() 强>
读取文件中Json形式的字符串,转换成Python类型
# !/usr/bin/python3 #,- *安康;编码:utf-8 - *安康; import json , 时间=strList json.load(开放(“listStr.json",,“r",, encoding =,“utf-8")) 打印(strList) #,[{& # 39;城市# 39;:,& # 39;北京& # 39;},,{& # 39;名字# 39;:,& # 39;蚂蚁& # 39;}] , 时间=strDict json.load(开放(“dictStr.json",,“r",, encoding =,“utf-8")) 打印(strDict) #,{& # 39;城市# 39;:,& # 39;北京& # 39;,,& # 39;名字# 39;:,& # 39;蚂蚁& # 39;}Python爬虫的json模块与jsonpath模块