如何将字典添加到文件中写入的 .json 列表
How to add a dictionary to .json list written in file
我正在尝试将 .json 词典添加到另一个文件中写入的 "Steps"
列表中。
{
"UPDATED AFTER IMPORT": {
"ID" : "UPDATED AFTER IMPORT",
"Name" : "Sample Name",
"Steps": []
}
}
我遇到了这个错误。
f["UPDATE AFTER IMPORT"].append({"Steps":[outputfile]})
TypeError: '_io.TextIOWrapper' object is not subscriptable
这是我试过的。
with open (stepjson, 'r+', encoding = 'utf-8') as jsonfile: #open step template
data = json.load(jsonfile)
data["Config"]["Script"].update({"Args":args_str}) #update args in step.json template
with open(json_dir+csvfilename +'.json', 'a') as f: #add edited step.json template to final .json file
outputfile = json.dumps(data,indent=4)
f["UPDATE AFTER IMPORT"].append({"Steps":[outputfile]})
您正在尝试将您的文件引用用作字典,这是行不通的。
这些方面的内容可能更接近您要查找的内容:
with open (stepjson, 'r+', encoding = 'utf-8') as jsonfile: #open step template
data = json.load(jsonfile)
data["Config"]["Script"].update({"Args":args_str})
with open(json_dir+csvfilename +'.json', 'w+') as f:
data_out = json.load(f)
data_out["UPDATE AFTER IMPORT"]["Steps"].append(data)
json.dump(data_out, f)
编辑:我更改了输出的打开模式,w+
可能是你想要使用的:你得到整个字典,修改它并完全写回
我正在尝试将 .json 词典添加到另一个文件中写入的 "Steps"
列表中。
{
"UPDATED AFTER IMPORT": {
"ID" : "UPDATED AFTER IMPORT",
"Name" : "Sample Name",
"Steps": []
}
}
我遇到了这个错误。
f["UPDATE AFTER IMPORT"].append({"Steps":[outputfile]})
TypeError: '_io.TextIOWrapper' object is not subscriptable
这是我试过的。
with open (stepjson, 'r+', encoding = 'utf-8') as jsonfile: #open step template
data = json.load(jsonfile)
data["Config"]["Script"].update({"Args":args_str}) #update args in step.json template
with open(json_dir+csvfilename +'.json', 'a') as f: #add edited step.json template to final .json file
outputfile = json.dumps(data,indent=4)
f["UPDATE AFTER IMPORT"].append({"Steps":[outputfile]})
您正在尝试将您的文件引用用作字典,这是行不通的。 这些方面的内容可能更接近您要查找的内容:
with open (stepjson, 'r+', encoding = 'utf-8') as jsonfile: #open step template
data = json.load(jsonfile)
data["Config"]["Script"].update({"Args":args_str})
with open(json_dir+csvfilename +'.json', 'w+') as f:
data_out = json.load(f)
data_out["UPDATE AFTER IMPORT"]["Steps"].append(data)
json.dump(data_out, f)
编辑:我更改了输出的打开模式,w+
可能是你想要使用的:你得到整个字典,修改它并完全写回