Python中的simplejson抛出值错误

Ahm*_*man 0 python google-app-engine json decode

我有一个JSON字符串,我发布到我的Python脚本.这是一个示例字符串:

{"uid":"1111111","method":"check_user"}
Run Code Online (Sandbox Code Playgroud)

在我的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)))
Run Code Online (Sandbox Code Playgroud)

任何想法可能是什么?我已经尝试从字符串中删除新的行,制表符和斜杠,甚至使用它来解码它.decode('string_escape')

agf*_*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)
Run Code Online (Sandbox Code Playgroud)

repr在请求时打印您的字符串,您应该看到它.

  • 更好的想法是追踪字符的原因并消除它,或使用正确的编码. (5认同)