我正在尝试使用Python脚本更新test.json文件。我只需要将"plan2"->"2"->"rooms"
的属性更改为3。请您帮我一下吗?
非常感谢
test.json
{
"plan1" : [{
"1": {
"rooms":"2",
"bathrooms":"1",
"kitchens":"1"
},
"2": {
"rooms":"1",
"bathrooms":"1",
"kitchens":"1"
}
}],
"plan2":[{
"1": {
"rooms":"3",
"bathrooms":"1",
"kitchens":"1"
},
"2": {
"rooms":"1",
"bathrooms":"1",
"kitchens":"1"
}
}]
}
test.py
import json
with open("test.json", "r+") as jsonFile:
data = json.load(jsonFile)
# need to change the "plan2"->"apartments"->"2"->"rooms" to 3
jsonFile.seek(0) # rewind
json.dump(data, jsonFile)
jsonFile.truncate()
答案 0 :(得分:1)
import json
with open("test.json", "r+") as jsonFile:
data = json.load(jsonFile)
# The change
d['plan2'][0]['1']['rooms'] = 3
jsonFile.seek(0)
json.dump(data, jsonFile)
jsonFile.truncate()
答案 1 :(得分:1)
您正在修改内存中的数据结构,而不是文件本身。为了完全安全,请分四个步骤进行操作:
将它们放在一起
import json
import tempfile
with open("test.json") as f:
data = json.loa(f)
data['apartments'][0]['2'][rooms] = 3
with tempfile.NamedTemporaryFile(delete=False) as f:
json.dump(data, f)
os.rename(f.name, "test.json")
这假定您的临时目录与JSON文件位于同一文件系统上,因此rename
操作是原子的。如果不是这种情况,请使用dir
的{{1}}参数指定在同一文件系统上是的目录。
答案 2 :(得分:0)