2012-02-06 52 views
1

我知道有类似的问题发布,但我认为我遇到的问题与他们相比稍有不同。请多多包涵;我在4个月前才开始使用Python,并且我确定我的不成熟显示!使用JSON的Unicode错误

我正在写一个程序,该程序使用Protovis插件在树状图中显示来自CSV文件的LinkedIn数据。据我所知,这个插件的设置是正确的,这些都是基于O'Reilly的Mining the Social Web。然而,当我在怠速运转我的代码,我得到了以下错误消息:

Traceback (most recent call last): 
File "C:/Users/Envy 15/Desktop/MASIDendo", line 115, in <module> 
    html = open(HTML_TEMPLATE).read() % (json.dumps(json_output),) 
    File "C:\Python27\lib\json\__init__.py", line 231, in dumps 
    return _default_encoder.encode(obj) 
    File "C:\Python27\lib\json\encoder.py", line 201, in encode 
    chunks = self.iterencode(o, _one_shot=True) 
    File "C:\Python27\lib\json\encoder.py", line 264, in iterencode 
    return _iterencode(o, 0) 
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 17: invalid start `byte` 

现在据我了解,此Unicode错误的原因是,有我在文件名中的一个非Unicode字符,但是我已经检查了他们,情况并非如此。我指向的代码部分是:

html = open(HTML_TEMPLATE).read() % (json.dumps(json_output),) 
f = open(os.path.join(os.getcwd(), 'out', OUT), 'w') 
f.write(html) 
f.close() 

print 'Data file written to: %s' % f.name 

# Open up the web page in your browser 

webbrowser.open('file://' + f.name) 

任何帮助,这将不胜感激!

+1

您的代码片段的第一行正在尝试做太多 - 创建JSON,加载模板以及为值创建最终的HTML。将这些分解为不同的步骤,您将更有可能看到发生了什么。 – 2012-02-06 13:50:34

回答

2

检查你的基地,验证json_data的内容,使用repr()或pprint.pprint()。

海峡和unicode对象有方法编码和解码接受错误的说法,这样的:"\x66\x89".decode("utf-8", "replace")

json.dumps数据编码成JSON,你通过它json_output输入很奇怪。

+1

我向你的智慧倾诉,先生:) – nfirvine 2012-02-23 20:05:17

+0

我感谢你:) – 2012-02-29 09:46:10

0

听起来像你的json_output对象有一个字符串,它不是unicode或unicode编码的。这不是文件名,这是一个问题。

+1

非常感谢你们两位! qarma的建议更好;我停留在打印再版(json_output)中,它给了我数据中的所有非Unicode字符。 – user1192309 2012-02-22 22:12:13