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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With