1

代码:

                body = '%s' % message.get_body()
                logging.error(body)
                parsed_body = json.loads(body)

正文包含:

[{u'content': u'Test\r\n', u'body_section': 1, u'charset': u'utf-8', u'type': u'text/plain'}, {u 'content': u'Test\r\n', u'body_section': 2, u'charset': u'utf-8', u'type': u'text/html'}]

错误:

line 67, in get
    parsed_body = json.loads(body)
  File "C:\Python27\lib\json\__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
  File "C:\Python27\lib\json\decoder.py", line 38, in errmsg
    lineno, colno = linecol(doc, pos)
TypeError: 'NoneType' object is not callable

有人知道出了什么问题吗?

4

1 回答 1

2

body是一个字符串(你可以用 '%s' % ... 得到它),所以它不应该包含 Python 字符串编码,例如u'content'.

这意味着 get_body() 返回一个复杂对象,并将'%s' % ...其转换为不是JSON 的 python 输出字符串,或者当 get_body 返回它时,某些东西已经在“修复”该字符串。然后错误在其他地方。

例子:

import json

# This is a correct JSON blob

body = '[{"content": "Test\\r\\n", "body_section": 1, "charset": "utf-8", "type": "text/plain"}, {"content": "Test\\r\\n", "body_section": 2
, "charset": "utf-8", "type": "text/html"}]'

# And this is a correct object
data = json.loads(body)

# If I were to print this object into a string, I would get 
# [{u'content': u'Test\r\n', u'type': u'text/plain', u'charset'...
# and a subsequent json.load would fail.

# Remove the comment to check whether the error is the same (it is not on
# my system, but I'm betting it depends on JSON implementation and/or python version)

# body = '%s' % data

print body

print json.loads(body)
于 2012-11-02T23:12:39.717 回答