2012-02-06 60 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