问题
{
"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