I have the following code so far:
for endpoint in endpoints:
post_aga = APINSRRequestsRouter()
response_obj_aga = post_aga.send_aga_post_request(endpoint)
if response_obj_aga:
if response_obj_aga[0] == "201":
id = response_obj_aga[1]["ACK"]["id"]
#dictionary with list code here
response_obj_aga is a list object containing a string, and a json object, as exampled:
['200', {'ACK': {'message': 'something happened', 'id': '319711da-20fd-4c94-bf8b-04735b435dd1'}}]
What I'm looking to do is every time I get a response_obj_aga object back containing an id, I want to apend that id to a list in a dictionary so I can save it as a JSON object in my database. So lets say I am expecting 3 separate responses, and have the following data:
['200', {'ACK': {'message': 'something happened', 'id': '17d362ae-a796-40fd-a1c3-0ff64e6f62e0'}}]
['200', {'ACK': {'message': 'something happened', 'id': '54e63ab8-aa1b-4d6f-a570-6ee7e52e2318'}}]
['200', {'ACK': {'message': 'something happened', 'id': 'b0a8ad20-b3e6-4100-963e-0f5e7f7e51f5'}}]
What I want to get at the end of my loop would be something like this:
{
"ids": [
"17d362ae-a796-40fd-a1c3-0ff64e6f62e0",
"54e63ab8-aa1b-4d6f-a570-6ee7e52e2318",
"b0a8ad20-b3e6-4100-963e-0f5e7f7e51f5"
]
}
What would be the most efficient way of doing this?
CodePudding user response:
Create a template object and append the IDs to it as the responses are read.
Working example:
import json
responses = [['200', {'ACK': {'message': 'something happened', 'id': '17d362ae-a796-40fd-a1c3-0ff64e6f62e0'}}],
['200', {'ACK': {'message': 'something happened', 'id': '54e63ab8-aa1b-4d6f-a570-6ee7e52e2318'}}],
['200', {'ACK': {'message': 'something happened', 'id': 'b0a8ad20-b3e6-4100-963e-0f5e7f7e51f5'}}]]
result = {'ids':[]}
for response in responses:
result['ids'].append(response[1]['ACK']['id'])
print(json.dumps(result, indent=2))
Output:
{
"ids": [
"17d362ae-a796-40fd-a1c3-0ff64e6f62e0",
"54e63ab8-aa1b-4d6f-a570-6ee7e52e2318",
"b0a8ad20-b3e6-4100-963e-0f5e7f7e51f5"
]
}
What your code should look like:
result = {'ids':[]}
for endpoint in endpoints:
post_aga = APINSRRequestsRouter()
response_obj_aga = post_aga.send_aga_post_request(endpoint)
if response_obj_aga:
if response_obj_aga[0] == "201":
id_ = response_obj_aga[1]["ACK"]["id"]
result['ids'].append(id_)
Note: id
is a built-in function in Python and shouldn't be used for a variable name.