Home > Mobile >  Reformat json as key value pairs with Python
Reformat json as key value pairs with Python

Time:11-11

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.

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.

CodePudding user response:

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,
    }
]
  • Related