-
正常导入
# 解析 json import json # 读取 accounts = json.load(open('./accounts.json', 'r', encoding="utf-8")) # 修改内容 account = accounts[0] account['result'] = 1 # 存入 with open('./accounts.json', 'r+', encoding='utf-8') as f: # 方式一: json.dump(accounts, f, indent=4) # 方式二: # f.write(json.dumps(accounts, indent=4)) -
如果
json中有中文,存入文件后显示的unicode编码,但是需要显示成中文# 解析 json import json # json info = { '订单需求信息': {'订单任务编号':'','观测目标名称':'','观测目标经度':''}, '任务规划结果': {'子订单任务编号':'','观测目标名称':''}, } # 存入 with open('./accounts.json', 'r+', encoding='utf-8') as f: # 方式一: json.dumps(info, f, indent=4, ensure_ascii=False) # 方式二: # f.write(json.dumps(accounts, indent=4, ensure_ascii=False))-
一定用
json.dumps(),dumps是将dict转化成str格式,否则报错。json.dumps()可以将该python字典转换成字符串类型,返回json字符串。 -
indent=4缩进4。 -
json.dumps()序列化时对中文默认使用的ascii编码,想输出真正的中文需要指定ensure_ascii=False。
-
-
基础用法
-
json.dumps()把数据类型转换成字符串 -
json.dump()把数据类型转换成字符串并存储在文件中 -
json.loads()把字符串转换成数据类型 -
json.load()把文件打开从字符串转换成数据类型
-