views:

269

answers:

2

Hello,

I'm loading a json string in Django using simplejson

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??

Many thanks,

g

+7  A: 

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']
Rudd Zwolinski
thank you. that was the problem. I have to figure out why things chance once passed through to view template.
givp
@givp: That's because django's template languages allows "dict.key" syntax to access dictionary items
hasen j
From this page: http://docs.djangoproject.com/en/dev/topics/templates/"Use a dot (.) to access attributes of a variable.Behind the scenesTechnically, when the template system encounters a dot, it tries the following lookups, in this order:Dictionary lookupAttribute lookupMethod callList-index lookup
celopes
+4  A: 

json.loads loads json into a python dictionary. So you must access it like a dictionary, i.e. data['key'].

Now, on the django template side of things, check the official django templates documentation.

Directly quoting:

Technically, when the template system encounters a dot, it tries the following lookups, in this order:

  • Dictionary lookup
  • Attribute lookup
  • Method call
  • List-index lookup

So basically, django templates allow you to access dictionary items using data.key syntax.

hasen j
great tip. thanks
givp