【发布时间】: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