如何在Python中从JSON文件生成索引列表?

时间:2019-07-19 19:45:13

标签: python json

我正在尝试使用jmespath操纵一个大的json文件。为此,我需要生成一个完整的路径列表以用作参考,因为并不需要所有项目。

这是一个示例json:

data = {
    "firstName": "Jane",
    "lastName": "Doe",
    "hobbies": ["running", "sky diving", "singing"],
    "age": 35,
    "children": [
        {
            "firstName": "Alice",
            "age": 6,
            "hobbies": ["swimming", "painting"]
        },
        {
            "firstName": "Bob",
            "age": 8,
            "hobbies": ["video games", "soccer"]
        }
    ]
}

我需要编写脚本以生成:

firstName.Jane
lastName.Doe
hobbies.running
hobbies.sky diving
hobbies.singing
age.35
children[0].firstname.Alice
children[0].age.6
children[0].hobbies.swimming
children[0].hobbies.painting
children[1].firstname.Bob
children[1].age.8
children[1].hobbies.video games
children[1].hobbies.soccer

JSON的深度可能达到3-4级。一直在尝试几种选择,但不能全神贯注于如何实现这一目标...

2 个答案:

答案 0 :(得分:1)

这应该适用于JSON的任何深度(不考虑递归限制):

data = {
    "firstName": "Jane",
    "lastName": "Doe",
    "hobbies": ["running", "sky diving", "singing"],
    "age": 35,
    "children": [
        {
            "firstName": "Alice",
            "age": 6,
            "hobbies": ["swimming", "painting"]
        },
        {
            "firstName": "Bob",
            "age": 8,
            "hobbies": ["video games", "soccer"]
        }
    ]
}

def traverese(d, current_key=''):
    if isinstance(d, dict):
        for k, v in d.items():
            yield from traverese(v, current_key + k + '.')
    elif isinstance(d, list):
        for i, vv in enumerate(d):
            yield from traverese(vv, current_key + '[' + str(i) + '].')
    else:
        yield current_key + str(d)

for index in traverese(data):
    print(index)

打印:

firstName.Jane
lastName.Doe
hobbies.[0].running
hobbies.[1].sky diving
hobbies.[2].singing
age.35
children.[0].firstName.Alice
children.[0].age.6
children.[0].hobbies.[0].swimming
children.[0].hobbies.[1].painting
children.[1].firstName.Bob
children.[1].age.8
children.[1].hobbies.[0].video games
children.[1].hobbies.[1].soccer

答案 1 :(得分:-1)

您可以使用递归代码。 这只是代码的参考,您可以使用该参考来递归检查json

for keys in data:
    #Here we are checking if type is list or dict
    if type(data[keys]) in [list,dict]:
        for x in data[keys]:
            print(x)