python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码

python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码

python的json.dumps方法默认会输出成这种格式"u535au5ba2u56ed",。
要输出中文需要指定ensure_ascii参数为False,如下代码片段:
json.dumps({'text':"中文"},ensure_ascii=False,indent=2)

import json #导入json格式

if __name__ == "__main__":
#datas = get_multiple_data()
#print(datas)
datas = {"text":"中文","polyline":"116.621248,41.02831"}
fl=open('../out/map_polyline.js', 'w')
#fl=open('../out/map_polyline.js', 'a')
fl.write("var polyline_data=")
#fl.write(json.dumps(datas))
fl.write(json.dumps(datas,ensure_ascii=False,indent=2))
fl.close()


解码json格式,可以用json.loads()函数的解析方法,
decode_json = json.loads(encoded_json)
print(type(decode_json)) #查看解码后的对象类型
print(decode_json)

原文地址:https://www.cnblogs.com/zdz8207/p/python_learn_note_26.html