<p>使用以下命令:</p>
<pre><code>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)
</code></pre>
<p><strong>为您的案例编辑:</strong>
如果json文件是<code>".\\file.json"</code>,那么</p>
<pre><code>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)
</code></pre>