问题思考
#python 嵌套列表
list_dict1=[{'java':{'year':'1996','url' :'www/baidu.com','score':[20,30,40]},'python':{'year':'1994','url' :'www/baidu.com','score':[50,60,70]}}]
#JSON
[
{
"java": {
"score": [
20,
30,
40
],
"url": "www/baidu.com",
"year": "1996"
},
"python": {
"score": [
50,
60,
70
],
"url": "www/baidu.com",
"year": "1994"
}
}
]
上篇简单介绍JSON 数据格式与 JSON 的转化。由于JSON格式与python集合(list,dict)嵌套格式类似,所以调用loads和dump函数进行数据格式转化。而对象与字符串的转换过程就是序列化
**
什么是序列化?
**
序列化就是将 对象的信息 或者 数据结构的信息通过一定的规则进行转换,可以达到文件存储或网络传输的效果。而反序列化就是通过序列化规则生成的字符串再反转为原始的数据类型,这就是反序列化。
这里我们可以引入 字符串 与 byte 之间的转换来理解 序列化与反序列化, 字符串与 byte 类型之间互相转换常用的 encode() 函数、与 decode() 函数,分别代表着编码与解码,所以有编码,就一定有解码 。套用在序列化来理解,既然存在序列化,那么就肯定有对应的反序列化。
对JSON字符串而言load和dump过程就是序列化与反序列化的过程。
可序列化的数据类型
可序列化:number、str、list、tuple、dict [字典是最常用的序列化数据类型]
不可序列化:class 、def (函数与实例化对象)、set 是无法进行序列化的
pickle模块
pickle模块与json模块一样可以进行序列化与反序列化,区别在于 pickle 是 Python 内置的序列化模块,而且不像 json 那么通用,它只能用于 python 自身来使用,其他语言可能就无法处理了
pickle模块的dumps函数将对象序列化为不可读的byte类型 由结果2:可知在对dumps结果进行loads反序列化后才为可读。
json解析方式
方法一:使用正则表达式
通过正则表达式re 匹配指定的value值
list_dict="[{'key':'123','imUrl': 'http://localhost:8888/notebooks/'},{'key':'456','imUrl': 'http://localhost:8088/notebooks/'}]"
json_arr=json.dumps(list_dict)
print(json_arr)
regex = r"'imUrl': '([\s\S]+?)'"
match_obj = re.findall(regex,json_arr)
print("正则结果:",match_obj)
方法二:使用jsonpath的路径解析json
pip install jsonpath 下载导入 jsonpath 模块,使用 jsonpath 模块进行解析
list_dict={"version": "2.2.1","result": {"pages": 1111,"data": [{"name": "java","imUrl": "http://localhost:8088/notebooks/","year":1998},
{"name": "python","imUrl": "http://localhost:8888/notebooks/","year": 2004}]}}
json_arr=json.dumps(list_dict)
print(json_arr)
namelist=jsonpath.jsonpath(list_dict, '$..name')
imUrllist=jsonpath.jsonpath(list_dict, '$..imUrl')
yearlist=jsonpath.jsonpath(list_dict, '$..year')
print("name 结果list:",namelist)
print("imUrl 结果list:",imUrllist)
print("year 结果list:",yearlist)
方法三:使用字典的数据结构性质解析json
由于JSON格式具有python dict字典格式,所以使用字典获取value的方式解析json
json_arr={"version": "2.2.1","result": {"pages": 1111,"data": [{"name": "java","imUrl": "http://localhost:8088/notebooks/","year":1998},
{"name": "python","imUrl": "http://localhost:8888/notebooks/","year": 2004}]}}
json_arr = json_arr["result"]["data"]
result_json_data = json_arr
namelist=[]
imUrllist=[]
yearlist=[]
for data in result_json_data:
namelist.append(data['name'])
imUrllist.append(data['imUrl'])
yearlist.append(data['year'])
print("name 结果list:",namelist)
print("imUrl 结果list:",imUrllist)
print("year 结果list:",yearlist)