I have a json file like this:
JavaScript
x
15
15
1
[
2
{
3
"id": "john",
4
"title": "tech",
5
"date": "2020/1/1",
6
"shift": "DAYS"
7
},
8
{
9
"id": "tom",
10
"title": "tech",
11
"date": "2021/5/5",
12
"shift": "NIGHT"
13
}
14
]
15
I need to re-create another JSON file based on this information. For example:
IF shift == NIGHT:
shiftHourStart = 22:00:00
shiftHourEnd = 06:00:00
So output should be like this:
JavaScript
1
18
18
1
[
2
{
3
"id": "john",
4
"title": "tech",
5
"shiftHourStart" = "22:00:00",
6
"shiftHourEnd" = "06:00:00"
7
"shift": "NIGHT"
8
},
9
{
10
"id": "tom",
11
"title": "tech",
12
"date": "2021/5/5",
13
"shiftHourStart" = "06:00:00",
14
"shiftHourEnd" = "15:00:00",
15
"shift": "DAY"
16
}
17
]
18
Advertisement
Answer
you can use dict.update
JavaScript
1
34
34
1
data = [
2
{
3
"id": "john",
4
"title": "tech",
5
"date": "2020/1/1",
6
"shift": "DAYS"
7
},
8
{
9
"id": "tom",
10
"title": "tech",
11
"date": "2021/5/5",
12
"shift": "NIGHT"
13
}
14
]
15
16
shift_mapping = {
17
'DAYS': { # or DAY whatever you have
18
"shiftHourStart": "22:00:00",
19
"shiftHourEnd": "06:00:00"
20
},
21
'NIGHT':{
22
"shiftHourStart": "06:00:00",
23
"shiftHourEnd": "15:00:00",
24
}
25
}
26
27
for each_shift in data:
28
if 'shift' in each_shift:
29
each_shift.update(shift_mapping[each_shift['shift']])
30
else:
31
print('Warning!! shift key does not exists!')
32
33
print(data)
34
JavaScript
1
13
13
1
[{'id': 'john',
2
'title': 'tech',
3
'date': '2020/1/1',
4
'shift': 'DAYS',
5
'shiftHourStart': '22:00:00',
6
'shiftHourEnd': '06:00:00'},
7
{'id': 'tom',
8
'title': 'tech',
9
'date': '2021/5/5',
10
'shift': 'NIGHT',
11
'shiftHourStart': '06:00:00',
12
'shiftHourEnd': '15:00:00'}]
13