python - 在python中更改json文件中的值

标签 python json python-3.x

所以我在 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/

相关文章:

python - 将 scipy.optimize.minimize 限制为整数值

java - JSON.decodeValue 解码异常

python - 关于Python语法

python - 为什么 list/dict 属性在装饰器之外保留值,而整数属性却没有?

Python - 从 excel 文件读取时间后没有得到正确的日期时间

xml - 在 node.js 中将 xml 转换为 json

c++ - rapidjson 正确的 json 创建

python - 如何提取beautifulsoup中最后一段标签文本?

python - 如何格式化 CSV 中的字典列表? - Python

javascript - 使用 Python Flask_socketio react socket.io-client 不处理事件