DeepBlue
DeepBlue

Reputation: 13

Extract specific element from JSON in python

How do I print just the "name" through this JSON format? in Python 2.7? I've basically tried a lot of examples from stack overflow, but they're doing json.load and I am not sure if I need that if I already have a JSON as an output. I'm trying to trim it to only what I need. Any help would be great. Thank you.

This is the example json and I only need the name PS: What is the 'u? I do not need that in my output.

{  u'data': {  u'items': [  {  u'created_at': 1401991208,
                           u'name': u'Great Deals Singapore',
                           u'path': u'organization/great-deals-singapore',
                           u'type': u'Organization',
                           u'updated_at': 1442343527},
                        {  u'created_at': 1415172261,
                           u'name': u'Secure Tech Alarm Systems Inc.',
                           u'path': u'organization/secure-tech-alarm-systems-inc-',
                           u'type': u'Organization',
                           u'updated_at': 1432082588},
                        {  u'created_at': 1307858564,
                           u'name': u'Foodcaching',
                           u'path': u'organization/foodcaching',
                           u'type': u'Organization',
                           u'updated_at': 1406611074},
                        {  u'created_at': 1421406244,
                           u'name': u'WP App Store',
                           u'path': u'organization/wp-app-store',
                           u'type': u'Organization',
                           u'updated_at': 1421406364},

Upvotes: 0

Views: 587

Answers (2)

Ronan Paixão
Ronan Paixão

Reputation: 8695

Your data is incomplete. Assuming you have the complete information, including valid JSON with appropriate block termination, you want to use json.load() to turn a str object (the JSON data is a string) into a dict. The u prefix denotes a Unicode string, which I think is not a valid JSON.

Due to your observations, it appears that what you have is not JSON, but a dict (dictionary) object, and as such you might be looking for:

for item in your_dict['data']['items']:
    print item['name']

Upvotes: 1

Chad S.
Chad S.

Reputation: 6631

assuming that that dict is assigned to some variable data you would just need to iterate the items and print the name for each one

for item in data['items']:
    print item['name']

Upvotes: 1

Related Questions