开发者

simplejson in Python throws value error

I've got a JSON string that I'm posting to my Python script. This is an example string:

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

In my Python code I simply call simplejson.loads( str ) where str is the JSON string from the request. The JSON string seems fine as when I print it at request time it's intact. However I get a 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, i开发者_运维技巧n decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))

Any ideas what it may be? I've tried removing new lines, tabs and slashes from the string, even decoding it using .decode('string_escape')


You've got some unprintable character in your string. I get the same error if I append a null byte to the end of the string, and printing it doesn't show the problem:

>>> 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)

Print the repr of your string at request time and you should see it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜