JSON解析错误“NoneType对象不可调用”?

时间:2012-11-02 23:04:37

标签: python json

代码:

                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

有人知道什么是错的吗?

1 个答案:

答案 0 :(得分:2)

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

这意味着要么get_body()返回一个复杂的对象,'%s' % ...正在将它转换为一个python输出字符串不是 JSON,或者某些东西已经“修复”了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)