0

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.

2
  • The code read_req['project']['code'] won't actually work for the JSON you provided. Did you mean read_req[0]['project']['code']? Commented Jul 21, 2017 at 4:17
  • Hey SethMMorton, I can get an individual project off the API. So the example provided would be working off the first project instance, providing the answer 123. Sorry for the confusion Commented Jul 21, 2017 at 4:22

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey SethMMorton, That worked perfectly! Thanks for your help mate!
0

You need for loop.

read_req = req.json()

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

5 Comments

If you look closely at the data structure the OP gave, you will notice that it is a list of dicts of dicts, so this won't quite work as written.
Hey Rahul, Thanks for getting back to us so quick. I tried that previously however it comes back with an error TypeError: list indices must be integers or slices, not str.
No, it actually doesn't. Try to copy-paste the JSON on your computer and use that. You get an IndexError.
Have you tried this in your local Python environment? This most recent update gives KeyError: 'project'.
I was mistaken as this is json array.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.