json.dumps 使用的ascii编码。
输出中文需要指定ensure_ascii=False
test_dic = {'a': '测', 'b': 'abc'}
print(test_dic)
# {'a': '测', 'b': 'abc'}
print(str(test_dic))
# {'a': '测', 'b': 'abc'}
print(str(test_dic).replace('测', '测试'))
# {'a': '测试', 'b': 'abc'}
# print(json.loads(str(test_dic))) # json.loads只认双引号
"""
Traceback (most recent call last):
File "C:/xll/代码/xz/other/create.py", line 29, in <module>
print(json.loads(str(test_dic)))
File "C:\Python36\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Python36\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python36\lib\json\decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
"""
print(json.loads(str(test_dic).replace('测', '测试')))
"""
Traceback (most recent call last):
File "C:/xll/代码/xz/other/create.py", line 29, in <module>
print(json.loads(str(test_dic)))
File "C:\Python36\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Python36\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python36\lib\json\decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
"""
print(json.dumps(test_dic))
# {"a": "\u6d4b", "b": "abc"}
print(json.dumps(test_dic).replace('测', '测试')) # 不识别中文
# {"a": "\u6d4b", "b": "abc"}
print(json.loads(json.dumps(test_dic).replace('测', '测试')))
# {'a': '测', 'b': 'abc'}
print(json.dumps(test_dic, ensure_ascii=False))
# {"a": "测", "b": "abc"}
print(json.dumps(test_dic, ensure_ascii=False).replace('测', '测试')) # 识别中文
# {"a": "测试", "b": "abc"}
print(json.loads(json.dumps(test_dic, ensure_ascii=False)))
# {'a': '测', 'b': 'abc'}
print(json.loads(json.dumps(test_dic, ensure_ascii=False).replace('测', '测试')))
# {'a': '测试', 'b': 'abc'}
参考:
https://zhuanlan.zhihu.com/p/37504880
https://www.cnblogs.com/biangbiang/archive/2013/02/19/2916780.html