Search code examples
pythondjangosimplejson

Inconsistency in ability to access data member of loaded JSON object


I'm loading a JSON string in Django using simplejson, thus:

obj = json.loads('{"name": "joe"}')
person = obj.name

This throws an error:

'dict' object has no attribute 'name'

but when I pass obj down to the view template and print it out via {{ obj.name }}, it works! Why?


Solution

  • I'm not sure how the Django aspect of it works, but the object you get from json.loads is a Python dict object. That means it doesn't have attributes of its keys, but you can access them like you would any other dictionary:

    obj = json.loads('{"name": "joe"}')
    person = obj['name']