【问题标题】:modifiy data of json file修改json文件的数据
【发布时间】:2023-01-11 01:00:36
【问题描述】:

如何使用 python 修改 json 文件的值? 所以我的 json 文件是:

{
  "roll no": "210",
  "school": "DAP",
  "city": "Delhi",
  "hobbies": [
    {
      "dance": "yes"
    },
 {
      "singing": "yes"
    },
 {
      "travel": "yes"
    },
            ]
}

所以这是我的json,我想替换如下值: roll no= 211 and travel="no" ,singing="no"

我努力了:

with open("student.json","r") as file:
    data=json.load(file)
    data["roll no"]= "211"
    
    for x in data:
        x["hobbies"]["singing"]="no"
        x["hobbies"]["travel"]="no"

            
        with open("student.json","w") as file:

        json.dump(data,file,indent=4)

我已经试过了,但我唯一能做的就是拒绝,但我无法改变爱好价值观 预期输出:

{
  "roll no": "211",
  "school": "DAP",
  "city": "Delhi",
  "hobbies": [
    {
      "dance": "yes"
    },
 {
      "singing": "no"
    },
 {
      "travel": "no"
    },
            ]
}

【问题讨论】:

  • 我想知道为什么你在访问列表项时没有收到 TypeError: list indices must be integers or slices, not str 错误,你应该将你的代码更新为 data["hobbies"][0]["travel"] = "no" 你应该在访问列表中的 dic 之前访问列表的索引。如果您只更新列表中的 2 项,则不需要 for 循环。
  • 您的with open("student.json","w") as file: 行中没有任何代码。你需要在那里放一些代码
  • @SembeiNorimaki:也许是这样,也许只是with open(...缩进了太多。

标签: python json json-value


【解决方案1】:

'hobbies' 是一个字典列表,所以你应该写:

with open("student.json","r") as file:
data=json.load(file)
data["roll no"] = "211"

for x in data["hobbies"]:
    for key in x:
        x[key]="no"

        
with open("student.json","w") as file:
    json.dump(data,file,indent=4)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2018-01-28
    相关资源
    最近更新 更多