json模块

json模块是python自带的模块,用于json与python数据之间的相互转换

网络爬虫第四章_json

JSON转换为python

网络爬虫第四章_json_02

案例

import json

#1,把json字符串,转换成python数据
#1.1 准备json字符串
json_str='''[{"provinceName":"美国","correntConfirmedCount":1179041,"confirmedCount":1643499},{"provinceName":"英国","correntConfirmedCount":222227,"confirmedCount":259559}]'''
#1.2 把json字符串,转换成python数据
rs = json.loads(json_str)
print(rs)
print(type(rs))
print(type(rs[0]))

# 2, 把json格式文件,转换成python类型的数据
# 2.1 构建指向该文件的文件对象

with open('data/test.json') as fp:
     #2.2 加载该文件对象,转换成python类型的数据
     python_list = json.load(fp)
     print(python_list)
     print(type(python_list))
     print(type(python_list))
     
                                         注意要在当前目录设置文件

运行结果

[{'provinceName': '美国', 'correntConfirmedCount': 1179041, 'confirmedCount': 1643499}, {'provinceName': '英国', 'correntConfirmedCount': 222227, 'confirmedCount': 259559}]
<class 'list'>
<class 'dict'>