将带有 json.dumps 的 UTF-8 文本保存为 UTF-8,而不是 \\u 转义序列

新手上路,请多包涵

示例代码(在 REPL 中):

 import json
json_string = json.dumps("ברי צקלה")
print(json_string)

输出:

 "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4"

问题:它不是人类可读的。我的(聪明的)用户想要验证甚至编辑带有 JSON 转储的文本文件(我宁愿不使用 XML)。

有没有办法将对象序列化为 UTF-8 JSON 字符串(而不是 \uXXXX )?

原文由 Berry Tsakala 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

使用 ensure_ascii=False 切换到 json.dumps() ,然后手动将值编码为 UTF-8:

 >>> json_string = json.dumps("ברי צקלה", ensure_ascii=False).encode('utf8')
>>> json_string
b'"\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94"'
>>> print(json_string.decode())
"ברי צקלה"

如果您正在写入文件,只需使用 json.dump() 并将其留给文件对象进行编码:

 with open('filename', 'w', encoding='utf8') as json_file:
    json.dump("ברי צקלה", json_file, ensure_ascii=False)

Python 2 的注意事项

对于 Python 2,还有一些注意事项需要考虑。如果您正在将其写入文件,您可以使用 io.open() 而不是 open() 生成一个文件对象,在您写入时为您编码 Unicode 值,然后使用 json.dump() 而不是写入该文件:

 with io.open('filename', 'w', encoding='utf8') as json_file:
    json.dump(u"ברי צקלה", json_file, ensure_ascii=False)

请注意, json 模块中存在一个错误, 其中 ensure_ascii=False 标志可以产生 unicodestr 对象的 _混合_。 Python 2 的解决方法是:

 with io.open('filename', 'w', encoding='utf8') as json_file:
    data = json.dumps(u"ברי צקלה", ensure_ascii=False)
    # unicode(data) auto-decodes data to unicode if str
    json_file.write(unicode(data))

在 Python 2 中,当使用编码为 UTF-8 的字节字符串(类型 str )时,请确保还设置了 encoding 关键字:

 >>> d={ 1: "ברי צקלה", 2: u"ברי צקלה" }
>>> d
{1: '\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94', 2: u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'}

>>> s=json.dumps(d, ensure_ascii=False, encoding='utf8')
>>> s
u'{"1": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4", "2": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4"}'
>>> json.loads(s)['1']
u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
>>> json.loads(s)['2']
u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
>>> print json.loads(s)['1']
ברי צקלה
>>> print json.loads(s)['2']
ברי צקלה

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 4.0 许可协议

写入文件

import codecs
import json

with codecs.open('your_file.txt', 'w', encoding='utf-8') as f:
    json.dump({"message":"xin chào việt nam"}, f, ensure_ascii=False)

打印到标准输出

import json
print(json.dumps({"message":"xin chào việt nam"}, ensure_ascii=False))

原文由 Hiep Tran 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题