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?
asked May 31, 2020 at 6:55
HoneyPoop
5232 gold badges9 silver badges28 bronze badges
2 Answers 2
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.
answered May 31, 2020 at 7:17
Leo Arad
4,4822 gold badges8 silver badges17 bronze badges
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)
answered May 31, 2020 at 7:21
Gabio
9,5643 gold badges17 silver badges38 bronze badges
Comments
lang-py
json.loads(load from string) and then append the names. Then you canjson.dumps(stringify) and rewrite the file