How to convert a nested json to the following format in python3?

穿精又带淫゛_ 提交于 2021-02-11 12:26:53

问题


{
  "key1": {
    "subfield1": 4,
    "subfield2": "hello"
    },
  "key2": 325,
  ...
}

No idea about how deeply nested it would be (max upto 4 - 5 levels). The only guarantee is that each key will be a string type. What I want to do is to convert the above JSON into the following format:

{
    "field1.subfield1": 4,
    "field1.subfield2": "hello", 
    "field2" : 325,
    ...,
    "fieldN.subfieldM.subsubfieldK. ...": "blah blah"
}

How can I do this?


回答1:


I am currently assuming that your dictionary is only containing other nested dictionaries or the final value.

My input data:

data = {
    "key1": {
        "subfield1": 4,
        "subfield2": {"subfield1": 4,
                      "subfield2": "hello"
                      },
    },
    "key2": 325,
}

Then by using a python generator, I can generate the nested key combinations and value using:

def flatten_dict(data, prefix=''):
    for key, value in data.items():
        if isinstance(value, dict):
            for item in flatten_dict(value, prefix=f"{prefix}{key}."):
                yield item
        else:
            yield f"{prefix}{key}", value

Then using that function on the data:

from pprint import pprint
pprint(dict(flatten_dict(data)))

results in the output:

{'key1.subfield1': 4,
 'key1.subfield2.subfield1': 4,
 'key1.subfield2.subfield2': 'hello',
 'key2': 325}


来源:https://stackoverflow.com/questions/65203641/how-to-convert-a-nested-json-to-the-following-format-in-python3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!