Appending data to a json file

dieter dieter at handshake.de
Tue Apr 4 01:31:30 EDT 2017


Dave <dboland9 at fastmail.fm> writes:

> I created a python program that gets data from a user, stores the data
> as a dictionary in a list of dictionaries.  When the program quits, it
> saves the data file.  My desire is to append the new data to the
> existing data file as is done with purely text files.

Usually, you cannot do that:
"JSON" stands for "JavaScript Object Notation": it is a text representation
for a single (!) JavaScript object. The concatenation of two
JSON representations is not a valid JSON representation.
Thus, you cannot expect that after such a concatenation, a single
call to "load" will give you back complete information (it might
be that a sequence of "load"s works).

Personally, I would avoid concatenated JSON representations.
Instead, I would read in (i.e. "load") the existing data,
construct a Python object from the old and the new data (likely in the form
of a list) and then write it out (i.e. "dump") again.




More information about the Python-list mailing list