1

I am new to Python and can't figure this out. I am trying to make an object from a json feed. I am trying to basically make a dictionary for each item in the json fed that has every property. The error I get is either TypeError: 'mediaObj' object is not subscriptable or not iterable

For bonus points, the array has many sub dictionaries too. What I would like is to be able to access that nested data as well.

Here is my code:

url = jsonfeedwithalotofdata.com
data = urllib.request.urlopen(url)
data = instagramData.read()
data = instagramData.decode('utf-8')
data = json.loads(data)
media = data['data']

class mediaObj:
    def __init__(self, item):
        for key in item:
            setattr(self, key, item[key])
            print(self[key])

    def run(self):
        return self['id']

for item in media:
    mediaPiece = mediaObj(item)

This would come from a json feed that looks as follows (so data is the array that comes after "data"):

"data": [
{
"attribution": null,
"videos": {},
"tags": [],
"type": "video",
"location": null,
"comments": {},
"filter": "Normal",
"created_time": "1407423448461",
"link": "http://instagram.com/p/rabdfdIw9L7D-/",
"likes": {},
"images": {},
"users_in_photo": [],
"caption": {},
"user_has_liked": true,
"id": "782056834879232959294_1051813051",
"user": {}
}

So my hope was that I could create an object for every item in the array, and then I could, for instance, say:

print(mediaPiece['id'])

or even better

print(mediaPiece['comments'])

And see a list of comments. Thanks a million

Wyetro
  • 8,439
  • 9
  • 46
  • 64
Startec
  • 12,496
  • 23
  • 93
  • 160
  • Think about what would happen if there was an key of `"run"` in the json feed. – John La Rooy Aug 08 '14 at 02:25
  • A. It will not. B. I did....nothing comes to mind – Startec Aug 08 '14 at 02:43
  • A. Will not _ever_? Can you be really sure? The same problem applies to any of your attributes you might add to the class in the future being overwritten in the instance. I guess it's a nice bit of "job security" B. It will replace your `run` method and lead to lots of fun bugs. – John La Rooy Aug 08 '14 at 03:06

1 Answers1

0

You're having a problem because you're using attributes to store your data items, but using list/dictionary lookup syntax to try to retrieve them.

Instead of print(self[key]), use print(getattr(self, key)), and instead of return self['id'] use return self.id.

Blckknght
  • 100,903
  • 11
  • 120
  • 169