要求
确保您的 python 文件采用 UTF-8 编码。否则你的非ascii字符将变成问号,?
。 Notepad++ 为此提供了出色的编码选项。
确保包含适当的字体。如果你想显示日文字符,那么你需要安装日文字体。
确保您的 IDE 支持显示 unicode 字符。
否则你可能会得到一个UnicodeEncodeError
抛出错误。
Example:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 22-23: character maps to <undefined>
PyScripter 对我有用。它包含在“Portable Python”中,位于http://portablepython.com/wiki/PortablePython3.2.1.1 http://portablepython.com/wiki/PortablePython3.2.1.1
- 确保您使用的是 Python 3+,因为此版本提供更好的 unicode 支持。
Problem
json.dumps() 转义 unicode 字符。
Solution
阅读底部的更新。或者...
将每个转义字符替换为解析后的 unicode 字符。
我创建了一个简单的 lambda 函数,名为getStringWithDecodedUnicode
就是这么做的。
import re
getStringWithDecodedUnicode = lambda str : re.sub( '\\\\u([\da-f]{4})', (lambda x : chr( int( x.group(1), 16 ) )), str )
Here's 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 ) )
Example
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 )
Output
json.dumps({'Japan': '日本'}) = {"Japan": "\u65e5\u672c"}
Decoded Unicode: {"Japan": "日本"}
Update
或者……直接过去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"}'