data_garden data_garden - 24 days ago 17
JSON Question

Python - update item in an existing json file

I want to update

float
values
inside my
json
file, structured like this:

{"Starbucks": {"Roads": 1.0, "Pyramid Song": 1.0, "Go It Alone": 1.0}}


So whenever I generate an already existing playlist, with the exact same items, I increment
key
values
by +
1.0
.

I have a file opened with
'append'
option

with open('pre_database/playlist.json', 'a') as f:
if os.path.exists('pre_database/playlist.json'):
#update json here
json.dump(playlist,f)


but this
'a'
method would append another
dictionary
to
json
, and it would generate
parsing
problems later on.

likewise, if I use
'w'
method, it would overwrite the file entirely.

what is the best solution for updating the values?

Answer

You could open the file in r+ mode (opens the file for both reading and writing), read in the JSON content, seek back to the start of the file, truncate it and then rewrite the modified dictionary back to the file:

if os.path.exists('pre_database/playlist.json'):
    with open('pre_database/playlist.json', 'r+') as f:
         playlist = json.load(f)
         # update json here
         f.seek(0)
         f.truncate()
         json.dump(playlist, f)
Comments