Home > Software design >  How to add a dictionary to .json list written in file
How to add a dictionary to .json list written in file

Time:05-25

I am trying to add a .json dictionary to the "Steps" list that's written in another file.

{
    "UPDATED AFTER IMPORT": {
        "ID"   : "UPDATED AFTER IMPORT",
        "Name" : "Sample Name",
        "Steps": []
    }
}

I am getting this error.

f["UPDATE AFTER  IMPORT"].append({"Steps":[outputfile]})
TypeError: '_io.TextIOWrapper' object is not subscriptable

Here's what I tried.

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]})

CodePudding user response:

You're trying to use your file reference as a dict, this cannot work. Something along these lines might be closer to what you are looking for:

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)

Edit: I changed the opening mode for the output, w is probably what you want to use: you get the whole dict, modify it and write it completely back

  • Related