python - 如何将 dict 转换为 unicode JSON 字符串?

标签 python json

使用标准库 json 模块,这对我来说似乎是不可能的。使用 json.dumps 时,它会自动转义所有非 ASCII 字符,然后将字符串编码为 ASCII。我可以指定它不转义非 ASCII 字符,但是当它试图将输出转换为 ASCII 时它会崩溃。

问题是 - 我不想要 ASCII!我只想将我的 JSON 字符串返回为 unicode(或 UTF-8 ) 字符串。有什么方便的方法吗?

这是一个演示我想要的例子:

d = {'navn': 'Åge', 'stilling': 'Lærling'}
json.dumps(d, output_encoding='utf8')
# => '{"stilling": "Lærling", "navn": "Åge"}'

当然,没有output_encoding这样的选项,所以这里是实际的输出:

d = {'navn': 'Åge', 'stilling': 'Lærling'}
json.dumps(d)
# => '{"stilling": "L\\u00e6rling", "navn": "\\u00c5ge"}'

总而言之 - 我想将 Python 字典转换为 UTF-8 JSON 字符串,无需任何转义。我该怎么做?


我会接受这样的解决方案:

  • 黑客(对dumps 进行预处理和后处理输入以达到预期效果)
  • 子类化 JSONEncoder (我不知道它是如何工作的,文档也不是很有帮助)
  • PyPi 上可用的第三方库

最佳答案

要求

  • 确保您的 python 文件以 UTF-8 编码。否则你的非 ascii 字符将变成问号,?。 Notepad++ 对此有出色的编码选项。

  • 确保您拥有合适的字体。如果要显示日语字符,则需要安装日语字体。

  • 确保您的 IDE 支持显示 unicode 字符。 否则,您可能会抛出一个 UnicodeEncodeError 错误。

例子:

UnicodeEncodeError: 'charmap' codec can't encode characters in position 22-23: character maps to <undefined>

PyScripter 适合我。它包含在 http://portablepython.com/wiki/PortablePython3.2.1.1 的“可移植 Python”中

  • 确保您使用的是 Python 3+,因为此版本提供更好的 unicode 支持。

问题

json.dumps() 转义 unicode 字符。

解决方案

阅读底部的更新。或者……

用解析的 unicode 字符替换每个转义字符。

我创建了一个名为 getStringWithDecodedUnicode 的简单 lambda 函数来执行此操作。

import re   
getStringWithDecodedUnicode = lambda str : re.sub( '\\\\u([\da-f]{4})', (lambda x : chr( int( x.group(1), 16 ) )), str )

这里的 getStringWithDecodedUnicode 作为常规函数。

def getStringWithDecodedUnicode( value ):
    findUnicodeRE = re.compile( '\\\\u([\da-f]{4})' )
    def getParsedUnicode(x):
        return chr( int( x.group(1), 16 ) )

    return  findUnicodeRE.sub(getParsedUnicode, str( value ) )

例子

testJSONWithUnicode.py(使用PyScripter作为IDE)

import re
import json
getStringWithDecodedUnicode = lambda str : re.sub( '\\\\u([\da-f]{4})', (lambda x : chr( int( x.group(1), 16 ) )), str )

data = {"Japan":"日本"}
jsonString = json.dumps( data )
print( "json.dumps({0}) = {1}".format( data, jsonString ) )
jsonString = getStringWithDecodedUnicode( jsonString )
print( "Decoded Unicode: %s" % jsonString )

输出

json.dumps({'Japan': '日本'}) = {"Japan": "\u65e5\u672c"}
Decoded Unicode: {"Japan": "日本"}

更新

或者...只需将 ensure_ascii=False 作为 json.dumps 的选项传递。

注意:您需要满足我在开头概述的要求,否则这将无法正常工作。

import json
data = {'navn': 'Åge', 'stilling': 'Lærling'}
result = json.dumps(d, ensure_ascii=False)
print( result ) # prints '{"stilling": "Lærling", "navn": "Åge"}'

关于python - 如何将 dict 转换为 unicode JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11699407/

相关文章:

javascript - 将 JS 对象传递到 HTML 字符串

java - 如何强制 RESTEasy 将数字输出为 json 中的字符串?

python - 在 WebDriver 中加载 Firefox 扩展时权限被拒绝

python - 错误: 'NameError: name ' terms_and_conditions' is not defined' when it is

Python 模块导入不起作用

python - 如何将 str.title 与其他语言一起使用?

json - 如何获取ffmpeg命令生成的json的key值?

python - 删除文本中的标记链接

ajax - jQuery:JSON 回调函数从未达到

java - Gson 从 Json 转换为带日期的数组列表