Karthik
Karthik

Reputation: 363

Python iterate data over JSON

I am trying to use the following script to perform a API query which outputs JSON. I'm iterating the JSON to print the certain field (name) of all JSON objects. My scripts prints all the items (name, classification, details, etc) and not the value.

Script:

import requests
import json

query_url = 'https://IP-address/api/request'

data = {"query":"days>50", "type":"json", "size":3}
response = requests.post(query_url, json=data, verify=False)

json_data = json.loads(response.text)


for name in json_data[0]:
        print (name)

JSON:

    [
    { 
        "name": "Android", 
        "classification": "public", 
        "detail": "Tag1, Tag2, Tag3", 
        "days": 70, 
        "date_last": "2017-07-21 05:48:07 AM"
    },
    { 
        "name": "iPhone", 
        "classification": "public", 
        "detail": "Tag4, Tag5, Tag6", 
        "days": 75, 
        "date_last": "2017-07-21 05:48:07 AM"
    },
    {
        "name": "Microsoft", 
        "classification": "public", 
        "detail": "Tag3, Tag8, Tag9", 
        "days": 90, 
        "date_last": "2017-07-21 05:48:07 AM"
    }
] 

Upvotes: 1

Views: 722

Answers (3)

flevinkelming
flevinkelming

Reputation: 690

If you want to iterate json_data and print each name you need to access each dictionary value by key:

for d in json_data:
    print(d['name'])

Or if you're only looking to print the 'name' of a specific dictionary, e.g. the first in the JSON data, iteration isn't necessary:

print(json_data[0]['name'])

Say you wanted to have the output printed in a specific way, you can use str.format:

for d in json_data:
    print("Name: {} Days: {}".format(d['name'], d['days']))

Upvotes: 2

gB08
gB08

Reputation: 182

you should access value of key 'name'

below is the code

for i in json_data[0]:
    print (i['name'])

Upvotes: 0

E. Ducateme
E. Ducateme

Reputation: 4248

My sense is that part of the problem is that we aren't clear on what we are looking at... so I suggest that we take a moment to look under the hood:

If we simply ask Python to show us each item in json_data, we see that Python has read in each dictionary in the list of dictionaries and will display them for us.

In [23]: for item in json_data:
    ...:     print(item)
    ...:
{'days': 70, 'classification': 'public', 'date_last': '2017-07-21 05:48:07 AM', 'name': 'Android', 'detail': 'Tag1, Tag2, Tag3'}
{'days': 75, 'classification': 'public', 'date_last': '2017-07-21 05:48:07 AM', 'name': 'iPhone', 'detail': 'Tag4, Tag5, Tag6'}
{'days': 90, 'classification': 'public', 'date_last': '2017-07-21 05:48:07 AM', 'name': 'Microsoft', 'detail': 'Tag3, Tag8, Tag9'}

From there, since each item is a dictionary, our next step is to then ask Python to extract just the values associated with the name key:

In [21]: for item in json_data:
    ...:     print(item['name'])
    ...:
    ...:
Android
iPhone
Microsoft

Upvotes: 2

Related Questions