面试题答案
一键面试import json
data = {
"中文键": "中文值"
}
with open('output.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
在这个过程中用到的json
模块方法及其作用:
json.dump()
:将Python对象(如字典)写入到文件对象中。参数data
是要写入的Python对象;f
是文件对象;ensure_ascii=False
确保中文正常显示而不是显示为ASCII编码形式;indent=4
使得生成的JSON文件有缩进,更易读。