简体   繁体   中英

Printing each instance of a single line item from a JSON using python

Does anyone know how to print and multiple instances of the same line from a JSON output?

The code I wish to decipher looks something similar to:

[
{
    "project": {
        "id": 6514847,
        "name": "Trial_1",
        "code": "123",
        "created_at": "2014-10-08T04:22:14Z",
        "updated_at": "2017-04-11T00:32:43Z",
        "starts_on": "2014-10-08"
    }
},

{
    "project": {
        "id": 6514864,
        "name": "Trial_2",
        "code": "456",
        "created_at": "2014-10-08T04:26:39Z",
        "updated_at": "2017-04-11T00:32:46Z",
        "starts_on": "2014-10-08"
    }
},
{
    "project": {
        "id": 12502453,
        "name": "Trial_3",
        "code": "789",
        "created_at": "2016-12-08T05:14:38Z",
        "updated_at": "2017-04-11T00:32:38Z",
        "starts_on": "2016-12-08"
    }
}
]

This code was a request.get()

I know I can print a single instance of this using

req = requests.get(url, headers=headers)
read_req = req.json()
trial = read_req['project']['code']
print(trial)  #123

The final product I wish to see is linking each Project Name to its relevant Project Code.

You have a list of dicts of dicts. To iterate over each "project" dict you just use a for loop.

for entry in read_req:
    trial = entry['project']['code']
    print(trial)

In this case, each time through the loop entry will be a dictionary containing the "project" key.

You need for loop.

read_req = req.json()

for project in read_req:
    print(project['project']['code'])

This should work for you:
assuming jsontxt is having input data

for i in range(0,len(jsontxt)):
    print jsontxt[i]['project']['name'], jsontxt[i]['project']['code']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM