2

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
2
  • Does this answer your question? python append to array in json object Commented May 31, 2020 at 6:58
  • load them first with json.loads (load from string) and then append the names. Then you can json.dumps (stringify) and rewrite the file Commented May 31, 2020 at 6:58

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

what is f.seek?
To overwrite the old JSON object without it just append the new object
This is answering your question?
Let me test it.
0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.