CareFree CareFree - 1 month ago 8
JSON Question

Python Objects and Lists within Dictionary

I'm pretty new to Python, so just working my way through understanding the data sets.

I'm having a little trouble producing the JSON output that is required for the API I am working with.

I am using

import json
json.load(data_file)


Working with Python dictionary and then doing

json.dump(dict, json_data)


My data needs to look like the following when it is output.

{
"event":{
"id":10006,
"event_name":"My Event Name",
},
"sub event":[

],
"attendees":[
{
"id":11201,
"first_name":"Jeff",
"last_name":"Smith",
},
{
"id":10002,
"first_name":"Victoria",
"last_name":"Baker",
},
]
}


I have been able to create the arrays in python and dump to json, but I am having difficulty creating the event "object" in the dictionary. I am using the below:

attendees = ['attendees']
attendeesdict = {}
attendeesdict['first_name'] = "Jeff"
attendees.append(attendeesdict.copy())


Can anyone help me add the "event" object properly?

Answer

In general, going from JSON to dictionary is almost no work because the two are very similar, if not identical:

attendees = [
    {
        "first_name": "Jeff"
        # Add other fields which you need here
    },
    {
        "first_name": "Victoria"
    }    
]

In this instance, attendees is a list of dictionaries. For the event:

event = {
    "id": 10006,
    "event_name": "My Event Name"
}

Putting it all together:

data = {
    "event": event,
    "sub event": [],
    "attendees": attendees
}

Now, you can convert it to a JSON object, ready to send to your API:

json_object = json.dumps(data)
Comments