官方给的参数注释:如果ensure_ascii=false且字符在字符串中包含obj,则返回值可包含non-ascii字符;否则,字符在JSON字符串中文被转义
s = {"name": "张三", "addr": "北京市"} print("ensure_ascii默认", json.dumps(s)) print("ensure_ascii=False", json.dumps(s, ensure_ascii=False)) print("ensure_ascii=True", json.dumps(s, ensure_ascii=True))
运行结果
ensure_ascii默认 {"name": "\u5f20\u4e09", "addr": "\u5317\u4eac\u5e02"} ensure_ascii=False {"name": "张三", "addr": "北京市"} ensure_ascii=True {"name": "\u5f20\u4e09", "addr": "\u5317\u4eac\u5e02"} 进程已结束,退出代码为 0
import ast import json dic1 = {"info": "abaaba", "recode": "200", "remsg": ""} dic2 = {"msg": "balabal", "state": "20000"} print(dic1) print(dic2) jd = json.dumps(str(dic2).replace("'", '"')) dic1.update({"remsg": ast.literal_eval(jd)}) print(json.dumps(dic1, ensure_ascii=False))
运行结果
{'info': 'abaaba', 'recode': '200', 'remsg': ''} {'msg': 'balabal', 'state': '20000'} {"info": "abaaba", "recode": "200", "remsg": "{\"msg\": \"balabal\", \"state\": \"20000\"}"} 进程已结束,退出代码为 0