json类型数据:
1. json数据转换成python数据
1.1 json字符串转换成python字符串
- import json
- jso = """[{"provinceName":"台湾","provinceShortName":"台湾","currentConfirmedCount":4823386,
- "confirmedCount":4846501,"suspectedCount":485,"curedCount":13742,"deadCount":9373,"comment":"",
- "locationId":710000,"statisticsData":"https://file1.dxycdn.com/2020/0223/045/3398299749526003760-135.json",
- "highDangerCount":0,"midDangerCount":0,"detectOrgCount":0,"vaccinationOrgCount":0,
- "cities":[],"dangerAreas":[]}]"""
- # 1.把json字符串转换成python字符串(即列表嵌套字典)
- # 1.1转换
- rs = json.loads(jso)
- print(rs)
1.2 json文件转换成python数据类型
- # 2.把json文件格式转换成python文件格式
- # 2.1 构建指向该文件的文件对象
- with open('1.json', 'r') as f:
- # 2.2 加载文件对象,转换成python类型数据
- python_list = json.load(f)
- print(python_list)
2. python数据类型转换成json数据类型
2.1 python字符串转换成json字符串
- import json
- # 1.把python字符串转换成json字符串
- list1 = """[{'provinceName': '台湾', 'provinceShortName': '台湾',
- 'currentConfirmedCount': 4823386, 'confirmedCount': 4846501, 'suspectedCount': 485,
- 'curedCount': 13742, 'deadCount': 9373, 'comment': '', 'locationId': 710000,
- 'statisticsData': 'https://file1.dxycdn.com/2020/0223/045/3398299749526003760-135.json',
- 'highDangerCount': 0, 'midDangerCount': 0, 'detectOrgCount': 0, 'vaccinationOrgCount': 0,
- 'cities': [], 'dangerAreas': []}]"""
- # 1.1 python转换成json
- python_list = json.dumps(list1, ensure_ascii=False) # 指定编码
- print(python_list)
2.2 python数据以json格式存储在磁盘中
- # 把python文件以json格式存储在磁盘中
- with open('2.json', 'w') as f:
- # ensure_ascii 可以改变编码方式
- json.dump(list1, f, ensure_ascii=False)