How to update a json file ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ZacB

Imagine I have my application’s data stored in a json file:

{
	"apples": 5,
	"bananas": 2,
	"kiwis": 0
}

How can I keep my data when I make an update of my game and a variable is added to it ? Like so :

{
	"apples": 5,
	"bananas": 2,
	"kiwis": 0,
	"oranges": 3
}

I’m searching for a clean way to do it

:bust_in_silhouette: Reply From: happycamper

You have to overwrite the entire line. Either you already have the full line ready to be written over the old one or you need to read the old data into a variable , make the addition, then write over the old line. There isnt a simple way to traverse the files unfortunately. If you have a lot of data to store its best to make it all organized in one dictionary per file. Dictionaries in dictionaries. …in dictionaries