0

I'm trying to figure out how to add the same object to every array.

I'm requesting data from the server for the "first game". When I get it back, it doesn't include any data referencing the first game. So I need to edit it before I send it to my server to save.

I have a json request that looks like this:

{
'dateTime': '2022-07-01T01:00:00.000000',
'httpStatus': 'OK',
'message': 'SUCCESS',
'details': None,
'detailsList': [
{
    'date': '2021-07-01T00:00:00',
    'tcount': 0,
    'first_name': 'Sam',
    'last_name': 'Smith'
},
{
    'user_reg_date': '2022-06-01T00:00:00',
    'tcount': 0,
    'first_name': 'Bob',
    'last_name': 'Jones'
}]

}

I'm trying to figure out how to add an object to each json array (hope I'm saying that the right way) before I then send it to a mongodb. In this example: 'game': 'first'

It would then look like this:

{
'dateTime': '2022-07-01T01:00:00.000000',
'httpStatus': 'OK',
'message': 'SUCCESS',
'details': None,
'detailsList': [
{
    'date': '2021-07-01T00:00:00',
    'tcount': 0,
    'first_name': 'Sam',
    'last_name': 'Smith',
    'game': 'first'
},
{
    'user_reg_date': '2022-06-01T00:00:00',
    'tcount': 0,
    'first_name': 'Bob',
    'last_name': 'Jones',
    'game': 'first'
}]

}

if there is a better way to do this, that would work as well.

1 Answers1

0

Your asking something similar to this question. But want to loop through a JSON array in Python.

You are not trying to add an 'object' to json 'array'. You have a JSON object, of which there are object members (or more commonly, properties). You have an array as an object member of which you want to modify each object in the array to add a new property.

The code below is the above link with some modification to fit your needs. request_data is the JSON object you give in your example above. You need enumerate to know which index to edit.

for index, item in enumerate(request_data['detailsList']):
     # Edit the array entry
     item["game"] = 'first'
     # Save it
     request_data['detailsList'][index] = item