Alexander Milano Manias Alexander Milano Manias - 1 month ago 6
JSON Question

from attribute in json on python

I called an url that returns me a json object with an attribute called

from
. So when i want to get this in python i try:

object.from.username

$ python sample_app.py
File "sample_app.py", line 63
print comment.from.username
^
SyntaxError: invalid syntax

Answer

from is a python keyword and should not be used as an attribute.

Lucky for you, when using the json library that comes with python, JSON objects become dictionaries instead:

object['from']['username']

For situations where you actually do have a object with a python keyword used as an attribute, you'd have to resort to using the getattr() function instead:

frm = getattr(object, 'from')