This might be a real noob question.
Thanks for helping.
I am receiving a json payload with the below structure
{
"response": true,
"error": null,
"msg": null,
"data": {
"slots": {
"04/26/2022": [
{
"0": 1650958200000,
"1": 19800,
"3": "1:00 PM",
"4": "26/Apr/2022 13:00 IST"
},
{
"0": 1650960000000,
"1": 19800,
"3": "1:30 PM",
"4": "26/Apr/2022 13:30 IST"
},
{
"0": 1650963600000,
"1": 19800,
"3": "2:30 PM",
"4": "26/Apr/2022 14:30 IST"
},
{
"0": 1650965400000,
"1": 19800,
"3": "3:00 PM",
"4": "26/Apr/2022 15:00 IST"
},
{
"0": 1650967200000,
"1": 19800,
"3": "3:30 PM",
"4": "26/Apr/2022 15:30 IST"
}
],
"04/24/2022": [],
"04/25/2022": [],
"04/23/2022": []
}
}
}
I want to create a new object with an array of the values of "0". Output should be
{
"slots": [
1650958200000,
1650960000000,
1650963600000,
1650965400000,
1650967200000
]
}
How would i go about doing this?
>Solution :
Here’s a straight-forward approach:
slots = payload["data"]["slots"] # Assumes payload has been converted from JSON to Python
slots_obj = {"slots": [d["0"] for _, lst in slots.items() for d in lst]}
Output:
{'slots': [1650958200000,
1650960000000,
1650963600000,
1650965400000,
1650967200000,
16539137693178]}
If you haven’t already, use json.loads to convert the JSON to a Python dictionary:
import json
payload = json.loads(payload)
The solution above uses what’s known as a list comprehension. It is equivalent to a for loop, which may be easier to understand:
timestamps = [] # Initialize an empty list to accumulate the Unix timestamps
# Iterate over each date, array pair in the slots dictionary using slots.items()
for _, slot_array in slots.items():
# Iterate over each inner dictionary
for slot_dict in slot_array:
# Grab the value at the "0" and append it to the timestamps accumulator
timestamps.append(slot_dict["0"])
# Finally create the new object, a dictionary with one key, "slots"
slots_obj = {"slots": timestamps}