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

Reformat json as key value pairs with Python

I have a JSON file that looks like the below:

{"Africa":
    {
        "invitee_event_type_page":
        {
            "Total Events": "194"
        },
        "invitee_meeting_cancelled":
        {
            "Total Events": "9"
        }
    },
    "Asia":
    {
        "invitee_event_type_page":
        {
            "Total Events": "127"
        },
        "invitee_meeting_scheduled":
        {
            "Total Events": "16"
        }
    }
}

I am trying to format this so that I something along the lines of the below:

output = [{"Asia - invitee_event_type_page": 127, "Asia - invitee_meeting_scheduled":16, "Africa - invitee_event_type_page": 194,"Africa - invitee_meeting_cancelled":9}]

I was trying the following but I’ve not had much luck. I’m quite new to all of this and I’m struggling to piece the different pieces of other answers together into something that is coherent. Any help would be greatly appreciated.

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

import re
import json

with open("ga2.json", "r") as f:
    data =json.load(f)

africa = (data)["Africa"]
output=[]

for key,value in africa.items():
    print(key,value["Total Events"])
    output= output+key,value["Total Events"]
print(output)

I get TypeError: can only concatenate list (not "str") to list.

>Solution :

You can use dict-comprehension to get your output:

dct = {
    "Africa": {
        "invitee_event_type_page": {"Total Events": "194"},
        "invitee_meeting_cancelled": {"Total Events": "9"},
    },
    "Asia": {
        "invitee_event_type_page": {"Total Events": "127"},
        "invitee_meeting_scheduled": {"Total Events": "16"},
    },
}

out = [
    {
        f"{k} - {kk}": int(vv["Total Events"])
        for k, v in dct.items()
        for kk, vv in v.items()
    }
]

print(out)

Prints:

[
    {
        "Africa - invitee_event_type_page": 194,
        "Africa - invitee_meeting_cancelled": 9,
        "Asia - invitee_event_type_page": 127,
        "Asia - invitee_meeting_scheduled": 16,
    }
]
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