Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Loop through JSON File

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)
like image 562
pee2pee Avatar asked Oct 22 '25 19:10

pee2pee


1 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'])
like image 72
Yevhen Kuzmovych Avatar answered Oct 25 '25 10:10

Yevhen Kuzmovych