0

I am trying to read a JSON file and iterate through it, for instance I am trying to print the children, or the firstname, or the hobbies etc...

The JSON file looks like this:

{
    "firstName": "Jane",
    "lastName": "Doe",
    "hobbies": ["running", "sky diving", "singing"],
    "age": 35,
    "children": [
        {
            "firstName": "Alice",
            "age": 6
        },
        {
            "firstName": "Bob",
            "age": 8
        }
    ]
},
{
    "firstName": "Mike",
    "lastName": "Smith",
    "hobbies": ["bowling", "photography", "biking"],
    "age":40,
    "children": [
        {
            "firstName": "Steve",
            "age": 10
        },
        {
            "firstName": "Sara",
            "age": 18
        }
    ]
}

I'm loading the json file using the following code:

import json


with open('test.json') as f:
    data = json.load(f)

and I can print parts of the first record fine like this:

print(data['children'])
print(data['hobbies'])

[{'firstName': 'Alice', 'age': 6}, {'firstName': 'Bob', 'age': 8}]
['running', 'sky diving', 'singing']

I'd like to iterate through the records though so I can print pieces of the 2nd entry as well (or 3rd, or 20th if applicable)

When I try this however:

for key, value in data.items():
    print(key, value)

It still just returns the first entry:

firstName Jane
lastName Doe
hobbies ['running', 'sky diving', 'singing']
age 35
children [{'firstName': 'Alice', 'age': 6}, {'firstName': 'Bob', 'age': 8}]

Any ideas?

3
  • 1
    You'd have to do the same for the inner nest of dictionaries. Commented Aug 26, 2018 at 3:47
  • 1
    Each element in the list is a dictionary, so you have to loop through the loop and apply the same you did to every element Commented Aug 26, 2018 at 3:49
  • 3
    That file should not have loaded -- it's clearly intended to be a list of dictionaries, but json lists must be enclosed in [ ]. Somehow, you only got the Jane Doe record. Commented Aug 26, 2018 at 3:52

2 Answers 2

1

The Problem you are facing is you are having the data as a single json.

You need to make it as an array. Something like this.

[{  // notice additional [
    "firstName": "Jane",
    "lastName": "Doe",
    "hobbies": ["running", "sky diving", "singing"],
    "age": 35,
    "children": [
        {
            "firstName": "Alice",
            "age": 6
        },
        {
            "firstName": "Bob",
            "age": 8
        }
    ]
},
{
    "firstName": "Mike",
    "lastName": "Smith",
    "hobbies": ["bowling", "photography", "biking"],
    "age":40,
    "children": [
        {
            "firstName": "Steve",
            "age": 10
        },
        {
            "firstName": "Sara",
            "age": 18
        }
    ]
}]  // notice additional ]

Then you need to loop it over the list and then as per what you have written. Something like this

import json

with open('abc.json') as f:
    data = json.load(f)

for element in data:
    for key, value in element.items():
        print(key, value)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. That throws a 'str has no attribute items' error but I get the gist I think. Looks like an issue with the json file itself, and a need for a second loop...
Glad I could help. :)
1

To covert your file be more std JSON, and open it add [ and ], to make it as json list. and whole code paste below:

import json

f = open("test_json.txt", "r")
contents = f.readlines()
f.close()


contents.insert(0, "[")

f = open("test_json.txt", "w")
contents = "".join(contents)
f.write(contents)
f.write("]")
f.close()


with open("test_json.txt", "r") as fd:
    d = json.load(fd)
    for i in d:
        print(i)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.