Joren
Joren

Reputation: 9925

JSON Parsing Error "NoneType object is not callable"?

Code:

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

Body contains:

[{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'}]

Error:

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

Anybody know what's wrong?

Upvotes: 1

Views: 5451

Answers (1)

LSerni
LSerni

Reputation: 57418

body is a string (you get it with '%s' % ...), so it shouldn't contain Python string-encoding such as u'content'.

This means that either get_body() returns a complex object, and '%s' % ... is converting it into a python-output string which is not JSON, or something is already "fixing" the string when get_body returns it. The error is then elsewhere.

Example:

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)

Upvotes: 2

Related Questions