How can i insert new json object to existing json file (in the middle of object) How can i insert new json object to existing json file (in the middle of object) json json

How can i insert new json object to existing json file (in the middle of object)


Step1: Read data

config = json.loads(open('filejson.json').read())

Step2: Update data (in python object)

config["Fiksi"].append(item)

Step3: Write all data (not append) back to file

with open('filejson.json','w') as f:    f.write(json.dumps(config))

On a side note, you can use json.load and json.dump instead for json.loads and json.dumps when dealing with files, so it will be

with open('filejson.json', 'r') as f:    config = json.load(f)config["Fiksi"].append(item)with open('filejson.json','w') as f:    json.dump(config, f)


The best way is to work with python objects:

  • import json
  • Load your file with json.load
  • Insert in the loaded dict
  • Dump to a file with json.dump


Just add:

f.write(json.dumps(data))