Reputation: 13
So i'm having a Json file as follow in vs code python:
{
"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"
}]
}
and i want to change the 'score' of a match, how can i do it? here's what i tried, but unexecutable:
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()
Traceback (most recent call last):
File "c:\Users\DELL.vscode\extensions\ms-python.python-2021.2.633441544\json_reading.py", line 40, in
updateScore()
File "c:\Users\DELL.vscode\extensions\ms-python.python-2021.2.633441544\json_reading.py", line 31, in updateScore
if item['Name']==Match_client:
KeyError: 'Name'
Upvotes: 0
Views: 45
Reputation: 468
I think you meant to type MatchID
instead of name
as there is no name
property in the 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()
Upvotes: 2