Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

filejson.json

{"Fiksi":[
    {
    "judul":"fiksi1",
    "pengarang":"pengarang1",
    "file":"namafiksi1.txt"
    },
    {
    "judul":"fiksi2",
    "pengarang":"pengarang2",
    "file":"namafiksi2.txt"
    }
],
"Non-Fiksi":[
    {
    "judul":"nonfiksi1",
    "penulis":"penulis1",
    "file":"namanonfiksi1.txt"
    },
    {
    "judul":"nonfiksi2",
    "penulis":"penulis2",
    "file":"namanonfiksi2.txt"
    }
]

I want to insert new object on tag "Fiksi". so the item can insert in the middle of file json. The object like this :

item = {"judul":"fiksi3", "pengarang":"pengarang3","file":"namafiksi3.txt"}

my code now :

config = json.loads(open('filejson.json').read())
with open('filejson.json','a') as f:
    data = f["Fiksi"].append(item)
    json.dumps(data)

its not working

like image 226
Rembulan Moon Avatar asked Feb 07 '23 18:02

Rembulan Moon


2 Answers

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)
like image 105
Muhammad Tahir Avatar answered Feb 12 '23 10:02

Muhammad Tahir


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
like image 43
Benjamin Avatar answered Feb 12 '23 09:02

Benjamin