赞
踩
{"name": "张三", "age": 18, "sex": "女"}
{ "msg": "SUCCESS", "code": 200, "time": "2023-12-08 13:14:20", "data": { "total": 86, "current": 1, "records": [ { "location_code": "421200000", "location_full_name": "湖北省咸宁市" }, { "location_code": "421202000", "location_full_name": "湖北省咸宁市咸安区" } ] } }
import json
data = '{"name": "张三", "age": 18, "sex": "女"}'
# 将 json 类型的数据转为 dict 类型
data_dict = json.loads(data)
print(data_dict)
# {'name': '张三', 'age': 18, 'sex': '女'}
print(type(data_dict))
# <class 'dict'>
import json
data_dict = {"name": "张三", "age": 18, "sex": "女"}
# 参数 ensure_ascii=False 是为了显示中文
data_json = json.dumps(data_dict, ensure_ascii=False)
print(data_json)
# {"name": "张三", "age": 18, "sex": "女"}
import json
PATH = r'1.json'
# data 的格式是 dict
with open(PATH, 'r', encoding='utf-8') as f:
data = json.load(f)
# 操作同 dict,如:
for key, value in data.items():
print(f'key = {key}, value = {value}')
print(data.get('msg'))
import json
PATH = r'1.json'
data = {'name': '张三', 'age': 18, 'sex': '女'}
with open(PATH, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。