python3 json.dumps 中文乱码问题

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值