简体   繁体   English

递归枚举 JSON 层次结构父/子到字典

[英]Recursive enumerate JSON hierarchy parent/child to dictionary

I'm looking to flatten a JSON hierarchy of unknown structure to a dictionary, capturing the full key hierarchy in the dictionary result to uniquely identify it.我希望将未知结构的 JSON 层次结构展平到字典中,捕获字典结果中的完整键层次结构以唯一标识它。

So far I am able to print the key:value pair for the all the parent/child nodes recursively but I am having trouble:到目前为止,我能够以递归方式打印所有父/子节点的键:值对,但我遇到了麻烦:

(1) figuring out how to pass the parent hierarchy keys for a recursive (child) execution and then reset it when it exits the child key. (1)弄清楚如何传递父层次结构键以进行递归(子)执行,然后在退出子键时将其重置。

(2) writing to a single dictionary result - when I define the dictionary within the recursive function, I end up creating multiple dictionaries... Do I need to wrap this function in a master function to avoid this? (2) 写入单个字典结果 - 当我在递归 function 中定义字典时,我最终会创建多个字典......我是否需要将这个 function 包装在一个主 ZC1C425268E68384F1AB50 到 this74C1457 中

Thanks!谢谢!

# flatten/enumerate example I'm using

with open('_json\\file.json') as f:
    data = json.load(f)

def parse_json_response(content):

    if len (content.keys()) > 1 :
        for key, value in content.items():
            if type(value) is dict:
                parse_json_response(value)
            else:
                print('{}:{}'.format(key,value))
    else:
        print(value)

if __name__ == '__main__':
    parse_json_response(data)
# current result as print
id = 12345
firstName = John
lastName = Smith
DOB = 1980-01-01
phone = 123
line1 = Unit 4
line2 = 3 Main st

# desired result to dictionary {}
id = 12345
fields.firstName = John
fields.lastName = Smith
fields.DOB = 1980-01-01
fields.phone = 123
fields.address.residential.line1 = Unit 4
fields.address.residential.line2 = 3 Main st

You can create the flattened dictionary (rather than just print values), by keeping track of the parent and recursing in the correct spot.您可以通过跟踪父级并在正确的位置递归来创建扁平化字典(而不仅仅是打印值)。 That might look something like:这可能看起来像:

d = {
    "ID": "12345",
    "fields": {
        "firstName": "John",
        "lastName": "Smith",
        "DOB": "1980-01-01",
        "phoneLand": "610292659333",
        "address": {
            "residential": {
                "line1": "Unit 4",
                "line2": "3 Main st"
            }
        }
    }
}

def flattenDict(d, parent=None):
    ret = {}
    for k, v in d.items():
        if parent:
            k = f'{parent}.{k}'
        if isinstance(v, dict):
            ret.update(flattenDict(v, k))
        else:
            ret[k] = v
    return ret

flat = flattenDict(d)

flat will be: flat将是:

{'ID': '12345',
 'fields.firstName': 'John',
 'fields.lastName': 'Smith',
 'fields.DOB': '1980-01-01',
 'fields.phoneLand': '610292659333',
 'fields.address.residential.line1': 'Unit 4',
 'fields.address.residential.line2': '3 Main st'}

You can also arrange the output to be a generator that yields tuples.您还可以将 output 安排为生成元组的生成器。 You can then pass this to dict() for the same result:然后,您可以将其传递给dict()以获得相同的结果:

def flattenDict(d):
    for k, v in d.items():
        if isinstance(v, dict):
            yield from ((f'{k}.{kk}', v) for kk, v in flattenDict(v))
        else:
            yield (k, v)

dict(flattenDict(d))

Try this below:在下面试试这个:

test = {
    "ID": "12345",
    "fields": {
        "firstName": "John",
        "lastName": "Smith",
        "DOB": "1980-01-01",
        "phoneLand": "610292659333",
        "address": {
            "residential": {
                "line1": "Unit 4",
                "line2": "3 Main st"
            }
        }
    }
}

def func(d, parent=""):
    for key, value in d.items():
        if isinstance(value, dict):
            func(value, parent=parent+key+".")
        else:
            print(f"{parent+key} = {value}")


func(test)

Result:结果:

ID = 12345
fields.firstName = John
fields.lastName = Smith
fields.DOB = 1980-01-01
fields.phoneLand = 610292659333
fields.address.residential.line1 = Unit 4
fields.address.residential.line2 = 3 Main st

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM