Reputation: 41
I have JSON file looks like this:
[
{
"lon": 0.0,
"altitude": 39000,
},
{
"lon": 0.0,
"altitude": 41000,
}
]
and I want save this file locally and updates from source file. For example: Refreshed source file have new data:
[
{
"lon": 19.84227,
"altitude": 41000,
},
{
"lon": 20.068794,
"altitude": 38000,
}
]
how to append local JSON file to add 2 new dictionaries at the end of file to have this:
[
{
values
},
{
values
}, <<< add " , " and new part of dictionaries
{
values
},
{
values
}
[
I trying append JSON files but I have this:
[
....
][ << [ and ] must be only at the beggining and end of file
....
]
how ?
Upvotes: 2
Views: 4630
Reputation: 41
I found simple solution:
Append JSON file with new data:
import os, json
with open('data.json', 'a') as fp:
json.dump(j_data, fp, indent = 2)
fp.close()
f = open('data.json','r')
old_data = f.read()
f.close()
search " ][ " and replace it with " , "
new_data = old_data.replace("][", ",")
save as new file
f = open('data_new.json','w')
f.write(new_data)
f.close()
remove old file and rename new file
os.remove('data.json')
os.rename('data_new.json', 'data.json')
Upvotes: 2