2011-09-22 24 views
0

我有一個JSON字符串,發佈到我的Python腳本。這是一個例子字符串:Python中的simplejson引發值錯誤

{"uid":"1111111","method":"check_user"} 

在我的Python代碼,我只需撥打simplejson.loads(str)其中str是從請求JSON字符串。 JSON字符串看起來很好,因爲當我在請求時打印它時,它完好無損。然而,我得到一個ValueError:

Extra data: line 1 column 41 - line 1 column 48 (char 41 - 48) 
Traceback (most recent call last): File 
"/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/_webapp25.py", 
line 703, in __call__ 
    handler.post(*groups) File "/Users/.../app/controller/api_controller.py", line 25, in post 
    req = simplejson.loads(req) File 
"/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_0_96/django/utils/simplejson/__init__.py", 
line 232, in loads 
    return cls(encoding=encoding, **kw).decode(s) File 
"/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_0_96/django/utils/simplejson/decoder.py", 
line 254, in decode 
    raise ValueError(errmsg("Extra data", s, end, len(s))) 

任何想法可能是什麼?我嘗試從字符串中刪除新行,製表符和斜線,甚至使用它解碼.decode('string_escape')

+0

這裏的堆棧跟蹤沒有幫助。儘量減少範圍,可能會幫助您識別錯誤。或者嘗試放置打印以確保值是正確的。如果沒有幫助,請嘗試消除依賴關係,理想情況下將所有內容放在單個文件中並重新發布。 –

+1

@RomanHwang其實,這是回答問題所需的所有信息。他解釋說,他知道這是字符串的(可打印部分)傳遞給JSON,因爲他正在打印它,並且他提供了錯誤。 – agf

回答

6

您的字符串中有一些不可打印的字符。我得到同樣的錯誤,如果我一個空字節追加到字符串的結尾,並print荷蘭國際集團它不顯示問題:

>>> import json 
>>> string = '{"uid":"1111111","method":"check_user"}\x00' 
>>> print string 
{"uid":"1111111","method":"check_user"} 
>>> print repr(string) 
'{"uid":"1111111","method":"check_user"}\x00' 
>>> json.loads(string) 
Traceback (most recent call last): 
    File "<interactive input>", line 1, in <module> 
    File "C:\Python27\Lib\json\__init__.py", line 326, in loads 
    return _default_decoder.decode(s) 
    File "C:\Python27\Lib\json\decoder.py", line 369, in decode 
    raise ValueError(errmsg("Extra data", s, end, len(s))) 
ValueError: Extra data: line 1 column 39 - line 1 column 40 (char 39 - 40) 

打印您的字符串的repr在請求時,你應該看到它。

+0

太棒了!那麼我怎麼把它們從琴絃上剪掉呢? –

+0

其實,它使用:str.replace('\ x00','') –

+0

@AhmedNuaman - 它不一定在字符串的末尾。這很可能就是每次都這樣做的壞角色。我會找出哪一個帶有'repr',然後執行'json.loads(mystring.replace('\ x00','')',無論字符/字符的值是否爲'\ x00' 。 – agf