Python JSON 编码问题
Python JSON encoding issues
我需要解析下载的 JSON 文件
url 文件
我得到 unicode:
{u'type': u'string', u'name': u'Podla\u017e\xed', u'value': u'2. podla\u017e\xed'}
我需要转换:
\u017e 到 ž
\xed 到 í
等等...
我该怎么做?
使用 unicode 时,您必须确保在程序中使用输入之前正确解码输入,并在将其序列化为字节时将其编码回 UTF-8
。前者好像你已经处理过了,所以你可以照原样使用字典。
当您想再次将字典保存为 json 时,您必须指定正确的编码并将其序列化为 UTF-8
。
import json
from io import open
with open('some_file.json', 'w', encoding='utf-8') as f:
f.write(json.dumps(some_dict, ensure_ascii=False))
您可以尝试使用代码打开。
参考:https://docs.python.org/2/library/codecs.html
示例代码。
import codecs
fileObj = codecs.open( "someFile", "r", "utf-8" )
u = fileObj.read()
我需要解析下载的 JSON 文件
url 文件
我得到 unicode:
{u'type': u'string', u'name': u'Podla\u017e\xed', u'value': u'2. podla\u017e\xed'}
我需要转换:
\u017e 到 ž
\xed 到 í
等等...
我该怎么做?
使用 unicode 时,您必须确保在程序中使用输入之前正确解码输入,并在将其序列化为字节时将其编码回 UTF-8
。前者好像你已经处理过了,所以你可以照原样使用字典。
当您想再次将字典保存为 json 时,您必须指定正确的编码并将其序列化为 UTF-8
。
import json
from io import open
with open('some_file.json', 'w', encoding='utf-8') as f:
f.write(json.dumps(some_dict, ensure_ascii=False))
您可以尝试使用代码打开。 参考:https://docs.python.org/2/library/codecs.html
示例代码。
import codecs
fileObj = codecs.open( "someFile", "r", "utf-8" )
u = fileObj.read()