How do I append a JSON file?

Viewed 157

How would I append a JSON file? I know how to append a JSON variable, but how do I append a file? for example, if my JSON file was:

{"people": [{"name" : "Michael Scott", "city": "Scranton"}]}

If I wanted to add another name to people, and that was in a JSON file, how would I do that?

2 Answers

You can try

with open("json_exp.txt", "r+") as f:
         json_obj = json.loads(f.read())
         json_obj["people"].append({"name":"new_person"})
         f.seek(0)
         json.dump(json_obj, f)

This code will read a text file that have a JSON object in it and will append a new value to the dict that made by the JSON object in the file then it will store the new JSON object to the file.

Let's say your destination json is:

# dest.json
{"people": [{"name" : "Michael Scott", "city": "Scranton"}]}

and you want to append the following json:

# source.json
{"name" : "Blah Blah", "city": "blah"}

Try:

import json

with open("destination.json") as fd, open("source.json") as fs:
    dest = json.load(fd)
    source = json.load(fs)
    dest["people"].append(source)
with open("destination.json", 'w') as fd:
    json.dump(dest, fd)
Related