Skip to content
Advertisement

How to create a JSON file from another JSON file based on IF condition! Python3

I have a json file like this:

[
      {
            "id": "john",
            "title": "tech",
            "date": "2020/1/1",
            "shift": "DAYS"
      },
      {
            "id": "tom",
            "title": "tech",
            "date": "2021/5/5",
            "shift": "NIGHT"
      }
]

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:

[
      {
            "id": "john",
            "title": "tech",
            "shiftHourStart" = "22:00:00",
            "shiftHourEnd" = "06:00:00"
            "shift": "NIGHT"
      },
      {
            "id": "tom",
            "title": "tech",
            "date": "2021/5/5",
            "shiftHourStart" = "06:00:00",
            "shiftHourEnd" = "15:00:00",
            "shift": "DAY"          
      }
]

Advertisement

Answer

you can use dict.update

data = [
      {
            "id": "john",
            "title": "tech",
            "date": "2020/1/1",
            "shift": "DAYS"
      },
      {
            "id": "tom",
            "title": "tech",
            "date": "2021/5/5",
            "shift": "NIGHT"
      }
]

shift_mapping = {
    'DAYS': { # or DAY whatever you have
        "shiftHourStart": "22:00:00",
            "shiftHourEnd": "06:00:00"
    },
    'NIGHT':{
        "shiftHourStart": "06:00:00",
        "shiftHourEnd": "15:00:00",
    }
}

for each_shift in data:
    if 'shift' in each_shift:
        each_shift.update(shift_mapping[each_shift['shift']])
    else:
        print('Warning!! shift key does not exists!')
    
print(data)
[{'id': 'john',
  'title': 'tech',
  'date': '2020/1/1',
  'shift': 'DAYS',
  'shiftHourStart': '22:00:00',
  'shiftHourEnd': '06:00:00'},
 {'id': 'tom',
  'title': 'tech',
  'date': '2021/5/5',
  'shift': 'NIGHT',
  'shiftHourStart': '06:00:00',
  'shiftHourEnd': '15:00:00'}]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement