python学习笔记06:json操作
json就是一串字符串(json只有双引号;字典是单引号)
1. 字典转成json
import json # json模块作用:python的数据类型和json相互转换的 d = {'key1': 'v1', 'key2': 'v2', 'key3': ' v3', 'name': '小明'} # 字典转成字符串(json) json_str = json.dumps(d, indent=4, ensure_ascii=False) # indent缩进字符,为了看着直观;ensure_ascii显示中文 print(json_str) # 将字典转成json写入文件--dumps和dump # dumps:先用dumps转成json,再写入文件 json_str = json.dumps(d, indent=4, ensure_ascii=False) with open('u1.json', 'w', encoding='utf-8') as f: f.write(json_str) # dump:直接用dump转成json写入文件 with open('u1.json', 'w', encoding='utf-8') as f: json.dump(d, f, indent=4, ensure_ascii=False)
2. json转成字典
import json json_str = """ { "key1": "v1", "key2": "v2", "key3": " v3", "name": "小明" } """ # 字符串(json)转成字典 dic = json.loads(json_str) print(dic) # 读文件里的json再转成字典--loads和load # loads:先读文件,再用loads传字符串,转字典 with open('u2.txt', encoding='utf-8') as f: content = f.read() print(json.loads(content)) # load:直接用load传文件(自动做了一次读文件),转成字典 with open('u2.txt', encoding='utf-8') as f: result = json.load(f) print(result)
json转成字典报错
# 若json格式不合法,报错 json_str = """ { 'key1': "v1", "key2": "v2", "key3": " v3", "name": "小明" } """ dic = json.loads(json_str) print(dic) # 查看json格式是否正确,网站校验:bejson.com
报错如下图:
校验json格式