Python:循环访问JSON文件

时间:2017-01-03 14:19:57

标签: python json

我不确定如何遍历顶级键A1和B6随机的特定结构。

我希望能够输出名称,x,y和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
    },
...

使用以下内容加载我的JSON

import json

with open('items.json') as data_file:    
    data = json.load(data_file)

1 个答案:

答案 0 :(得分:3)

遍历.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'])