I have this specific scenario where I'm going to get a JSON that could have multiple Objects. From the Multiple Objects I will create a new Json that can have nested arrays growing by n amount depending on some json object values.
I hoping there is a better way to do this. Maybe my example below is the best way? I took a look at https://realpython.com/python-data-classes/ but I don't think that will help since it seems complicated to turn the dataclass object into another json.
Update: I think I will ingest the original json object into a dataclass. Then iterate over the objects.
Example Input: Note that 3 and 4 are break start and end times. Which is why you will see the start and end times show up in the break array.
[{
"name": "Jay",
"clock_type": 1,
"start": "4am"
}, {
"name": "Jay",
"clock_type": 4,
"start": "5am"
},
{
"name": "Jay",
"clock_type": 3,
"end": "6am"
},
{
"name": "Jay",
"clock_type": 4,
"start": "7am"
},
{
"name": "Jay",
"clock_type": 3,
"end": "8am"
}]
Example output:
{
"name": "Jay",
"start": "4am",
"break": [{
"start": "5am",
"end": "6am"
}, {
"start": "7am",
"end": "8am"
}]
}
What i'm doing right now is looping through the array, and building the punch dynamically based on the "clock_type".
import json
def write_new_json(data):
request = {}
break_count = 0
for i in data:
# 1 = New Object. First Clock In
if i['clock_type'] in [1]:
request.update({"name": i["name"],
"start": i["start"]})
# 3 = Break End
if i['clock_type'] in [3]:
request["break"][break_count].update({"end": i["end"]})
break_count += 1
# 4 = Break start. If there is already a breaks object, then we do not create a breaks array,
# we just append to the existing one.
if i['clock_type'] in [4]:
if break_count == 0:
request.update({"break": []})
request["break"].append({"start": i["start"]})
# 2 = Not in the example, but a punch of 2 would reset break_count to 0.
return request
with open('example.json') as f:
api_request = write_new_json(json.load(f))
print(json.dumps(api_request))