如何根据IF条件从另一个JSON文件创建JSON文件!Python3

2024-05-16 11:28:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个json文件,如下所示:

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

我需要根据这些信息重新创建另一个JSON文件。例如:

如果班次==夜间:

shiftHourStart=22:00:00

班次结束=06:00:00

所以输出应该是这样的:

[
      {
            "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"          
      }
]

Tags: 文件信息idjsondateshifttitlejohn
2条回答

您可以使用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'}]

使用以下命令:

import json
json_text = """[
      {
            "id": "john",
            "title": "tech",
            "date": "2020/1/1",
            "shift": "DAYS"
      },
      {
            "id": "tom",
            "title": "tech",
            "date": "2021/5/5",
            "shift": "NIGHT"
      }
]
"""
n_dict = json.loads(json_text)
if n_dict[0]['shift'] == 'DAY':
    n_dict[0]["shiftHourStart"]="06:00:00"
    n_dict[0]["shiftHourEnd"] = "15:00:00"
else:
    n_dict[0]["shiftHourStart"]="22:00:00"
    n_dict[0]["shiftHourEnd"] = "06:00:00"
new_json = json.dumps(n_dict)
print(new_json)

为您的案例编辑: 如果json文件是".\\file.json",那么

import json
with open('.\\file.json') as f:
  json_text = json.load(f)
n_dict = json.loads(json_text)
if n_dict[0]['shift'] == 'DAY':
    n_dict[0]["shiftHourStart"]="06:00:00"
    n_dict[0]["shiftHourEnd"] = "15:00:00"
else:
    n_dict[0]["shiftHourStart"]="22:00:00"
    n_dict[0]["shiftHourEnd"] = "06:00:00"
with open('.\\new_file.json', 'w') as json_file:
  json.dump(n_dict, json_file)

相关问题 更多 >