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?
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)
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)
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.