使用python json.loads解析unicode输入

Sof*_*tic 16 python django unicode json

在Python中加载JSON字符串的最佳方法是什么?

我想使用json.loads来处理这样的unicode:

import json
json.loads(unicode_string_to_load)
Run Code Online (Sandbox Code Playgroud)

我也尝试使用值'utf-16'提供'encoding'参数,但错误并没有消失.

完整的SSCCE,错误:

# -*- coding: utf-8 -*-
import json
value = '{"foo" : "bar"}'
print(json.loads(value)['foo'])     #This is correct, prints 'bar'

some_unicode = unicode("degradé")  
#last character is latin e with acute "\xe3\xa9"
value = '{"foo" : "' + some_unicode + '"}'
print(json.loads(value)['foo'])            #incorrect, throws error
Run Code Online (Sandbox Code Playgroud)

错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 
6: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

Sof*_*tic 9

我使用'latin-1'将字符串转换为unicode字符串,修复了错误:

UnicodeDecodeError: 'utf16' codec can't decode byte 0x38 in 
position 6: truncated data
Run Code Online (Sandbox Code Playgroud)

固定代码:

import json

ustr_to_load = unicode(str_to_load, 'latin-1')

json.loads(ustr_to_load)
Run Code Online (Sandbox Code Playgroud)

然后错误就不会被抛出.

  • BTW,`latin-1`是`iso-8859-1`的旧名称,这些天你更有可能看到`iso-8859-15`-唯一的区别是后者包括欧元符号.如果用`-1`解码并且字符串用`-15`编码,那么它将大部分没问题,但是当你打印或显示它们时,欧洲标志看起来非常奇怪. (5认同)
  • 名称unicode未定义,出错 (3认同)

Ale*_*lli 6

OP澄清(在评论中!)......:

源数据是巨大的unicode编码字符串

然后你必须知道它使用的许多unicode编码中的一个 - 显然不是'utf-16',因为那个失败了,但还有很多其他的 - 'utf-8','iso-8859-15',以及等等.您可以尝试全部操作,也print repr(str_to_load[:80])可以将其显示的内容粘贴到您的问题编辑中,以便我们代表您猜测! - ).


jer*_*ran 5

我找到的最简单的方法是

import simplejson as json
Run Code Online (Sandbox Code Playgroud)

这样你的代码保持不变

json.loads(str_to_load)
Run Code Online (Sandbox Code Playgroud)

参考:https://simplejson.readthedocs.org/en/latest/