文章目录
JSON 模块的使用
import json
# 区别: josn.loads()的对象是python对象, json.load()的对象是文件对象,
# 两者都有各自的适用场景, 根据场景不同,选择适合的方法即可.
def read_file(file):
with open(file, "r", encoding='utf8') as f:
result = f.read()
return json.loads(result)
with open(file, 'r', encoding='utf8' ) as f:
result = json.load(f)
# dump与dumps
result = {
"test":{
"key": "value"
}
}
with open(file, 'w', encoding="utf8") as f:
json.dump(result, f, indent=4, separators=(",", ":"), ensure_ascii=False)
#ensure_ascii=False,可以保持中文可读,默认为True
with open(file, 'w', encoding="utf8") as f:
f.write(json.dumps(result, indent=4, separators=(",", ":"), ensure_ascii=False)) # 注意层级关系
# 这里只是介绍了两种方法, 对于两者的性能,还没有做出比较.