# 如何读写json数据
import json
l = [1, 2, 'abc', {'name': 'Bob', 'age': 13}]
print(json.dumps(l))
d = {'b': None, 'a': 5, 'c': 'abc'}
print(json.dumps(d))
# 压缩字符串长度,去掉空格
print(json.dumps(d, separators=[',', ':']))
# 对输出的键排序
print(json.dumps(d, sort_keys=True))
# 将json字符串转换为列表
l2 = json.loads('[1, 2, "abc", {"name": "Bob", "age": 13}]')
print(l2[2])
# 将json字符串转换为字典
d2 = json.loads('{"b":null,"a":5,"c":"abc"}')
print(d2['a'])
# load 和 dump 是对文件的读写
with open('demo.json', 'w') as f:
json.dump(l, f)