所以我在 vs 代码 python 中有一个 Json 文件,如下所示:
{
"matches_details":[
{
"MatchID": "Liverpool-Manchester United",
"Score": "5-0",
"Date": "17/12/2020",
"Time": "16:00",
"Yellow cards": "2",
"Red cards": "1",
"State": "FT"},
{
"MatchID": "Crystal Palace-Chelsea",
"Score": "3-2",
"Date": "20/1/2021",
"Time": "12:00",
"Yellow cards": "1",
"Red cards": "0",
"State": "HT"
}]
}
我想更改比赛的“分数”,我该怎么做?这是我尝试过的,但无法执行:
Time_client='12:00'
Date_client='20/1/2021'
Match_client='Crystal Palace-Chelsea'
Score_client='10-0'
f = open('datngu.json','r+')
data = json.load(f)
f.close()
for item in data['matches_details']:
if item['Name']==Match_client:
if item['Time']==Time_client:
if item['Date']==Date_client:
item['Score']=item['Score'].replace(Score_client,item['MatchID'])
f2=open('datngu.json','r+')
json.dump(data,f2)
f2.close()
回溯(最近一次调用最后一次):文件“c:\Users\DELL.vscode\extensions\ms-python.python-2021.2.633441544\json_reading.py”,第 40 行,在
更新分数()
文件“c:\Users\DELL.vscode\extensions\ms-python.python-2021.2.633441544\json_reading.py”,第 31 行,在 updateScore
如果 item['Name']==Match_client:
key 错误:'名称'
最佳答案
我想你的意思是输入 MatchID
而不是 name
因为没有 name
JSON 中的属性:
Time_client='12:00'
Date_client='20/1/2021'
Match_client='Crystal Palace-Chelsea'
Score_client='10-0'
f = open('datngu.json','r+')
data = json.load(f)
f.close()
for item in data['matches_details']:
if item['MatchID']==Match_client:
if item['Time']==Time_client:
if item['Date']==Date_client:
item['Score']=item['Score'].replace(Score_client,item['MatchID'])
f2=open('datngu.json','r+')
json.dump(data,f2)
f2.close()
关于python - 在python中更改json文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67275991/