rjuzzle
rjuzzle

Reputation: 7

Does json.dump() in python rewrite or append a JSON file

When working with json.dump() I noticed that it appears to be rewriting the entire document. Is this correct, and is there another way to append to the dictionary like .append() deos with lists?

When I write the function like this and change the key value (name), it would appear that the item is being appended.

filename = "infohere.json"
name = "Bob"
numbers = 20

#Write to JSON
def writejson(name = name, numbers = numbers):
    with open(filename, "r") as info:
        xdict = json.load(info)
    
    xdict[name] = numbers

    with open(filename, "w") as info:
        json.dump(xdict, info)

When you write it out like this however, you can see that the code clearly writes over the entire dictionary/json file.

filename = infohere.json
dict = {"Bob":23, "Mark":50}
dict2 = {Ricky":40}

#Write to JSON
def writejson2(dict):
    with open(filehere, "w") as info:
        json.dump(dict, info)

writejson(dict)
writejson(dict2)

In the second example it only ever shows up the last date input leading me to believe that this is rewriting the entire document. If the case is that it writes the whole document during each json.dump, does this cause issues with larger json file, if so is there another method like .append() but for dealing with json.

Thanks in advance.

Upvotes: 0

Views: 3439

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295649

Neither.

json.dump doesn't decide whether to delete prior content when it writes to a file. That decision happens when you run open(filehere, "w"); that is what deletes old content.

But: Normal JSON isn't amenable to appends.

A single JSON document is one object. There are variants on the format that allow multiple documents in one file, the most common of which is JSONL (which has one JSON document per line). Unless you're using such a format, trying to append JSON to a non-empty file usually won't result in something that can be successfully parsed.

Upvotes: 3

Related Questions