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

Upvotes: 1

Views: 351

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123930

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')

Upvotes: 3

Related Questions