Python: Loop through JSON File
Question:
I’m not sure how to loop through this particular structure where the top level keys A1 and B6 are random.
I want to be able to output name, x, y and yr
{
"A1": {
"msgs": ["Something there"],
"name": "Mary White",
"x": 132,
"y": 73,
"yr": 1978
},
"B6": {
"msgs": ["Something here"],
"name": "Joe Bloggs",
"x": 132,
"y": 73,
"yr": 2016
},
...
Using the following to load my JSON
import json
with open('items.json') as data_file:
data = json.load(data_file)
Answers:
Iterate through .values()
:
import json
with open('data.json') as data_file:
data = json.load(data_file)
for v in data.values():
print(v['x'], v['y'], v['yr'])
I’m not sure how to loop through this particular structure where the top level keys A1 and B6 are random.
I want to be able to output name, x, y and yr
{
"A1": {
"msgs": ["Something there"],
"name": "Mary White",
"x": 132,
"y": 73,
"yr": 1978
},
"B6": {
"msgs": ["Something here"],
"name": "Joe Bloggs",
"x": 132,
"y": 73,
"yr": 2016
},
...
Using the following to load my JSON
import json
with open('items.json') as data_file:
data = json.load(data_file)
Iterate through .values()
:
import json
with open('data.json') as data_file:
data = json.load(data_file)
for v in data.values():
print(v['x'], v['y'], v['yr'])