Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flatten nested json file

I have the following json file:

{
    "Teams" : ["Dortmund", "Real Madrid"] ,
    "Countries" : [
        "Colombia",
        {
            "Italia" : ["Milan", "Inter", "Juventus"]
        },
        {
            "France" : ["PSG", "Lille"]
        },
        "China"
    ]
}

I want to flatten it in a dictionary, so that it looks like this:

{"Teams": ["Dortmund", "Real Madrid"], "Countries":["Colombia", "Italia", "Milan", "Inter", "Juventus", "France", "PSG", "Lille", "China" ]}

I made this recursive fuction:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def flatten_json(data):
    result = {}
    for key, value in data.items():
        if isinstance(value, dict):
            result.update(flatten_json(value))
        elif isinstance(value, list):
            for i, item in enumerate(value):
                result.update(flatten_json(item))
        else:
            result[key] = value
    return result

But I get this error:

Traceback (most recent call last):
  File "prueba.py", line 46, in <module>
    flattened_dict = flatten_json(organigram)
  File "prueba.py", line 36, in flatten_json
    result.update(flatten_json(item))
  File "prueba.py", line 31, in flatten_json
    for key, value in data.items():
AttributeError: 'str' object has no attribute 'items'

Does anyone know how I can fix it, or how I can achieve the flattening of the json as I want it. Thanks in advance.

>Solution :

You can try:

dct = {
    "Teams": ["Dortmund", "Real Madrid"],
    "Countries": [
        "Colombia",
        {"Italia": ["Milan", "Inter", "Juventus"]},
        {"France": ["PSG", "Lille"]},
        "China",
    ],
}


def flatten(o):
    if isinstance(o, dict):
        for k, v in o.items():
            yield k
            yield from flatten(v)
    elif isinstance(o, list):
        for v in o:
            yield from flatten(v)
    else:
        yield o


out = {k: list(flatten(v)) for k, v in dct.items()}
print(out)

Prints:

{
    "Teams": ["Dortmund", "Real Madrid"],
    "Countries": [
        "Colombia",
        "Italia",
        "Milan",
        "Inter",
        "Juventus",
        "France",
        "PSG",
        "Lille",
        "China",
    ],
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading