0

I've got the following JSON file named test.json

{"a": ["First letter of alphabet"],"b":["Second letter of alphabet"], "c":["Third letter"]}

I want to add new values to the dictionary in the JSON file

import json
data = json.load(open("test.json","r+"))
data["d"] = [str("fourth letter")]
print(data)

The code above prints the following results to the terminal

{"a": ["First letter of alphabet"],"b":["Second letter of alphabet"], "c":["Third letter"],"d":["fourth letter"]}

But my JSON file remains unchanged

{"a": ["First letter of alphabet"],"b":["Second letter of alphabet"], "c":["Third letter"]}

I want the new values to be stored in the JSON file like this

{"a": ["First letter of alphabet"],"b":["Second letter of alphabet"], "c":["Third letter"],"d":["fourth letter"]}
1
  • I am not being able to reproduce the result. Using your code I am getting your expected output. Commented Mar 3, 2021 at 12:13

1 Answer 1

2

You're adding the column on the variable, but for save that new info on json you have to overwrite your json file or create a new one.

Example:

import json
data = json.load(open("test.json","r+"))
data["d"] = [str("fourth letter")]

with open("test.json", "w") as jsonFile:
# for creating a new file, just rename the test.json to another name
    json.dump(data, jsonFile)

Alternatively, like said here: How to update json file with python, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous"

with open("test.json", "r+") as jsonFile:
    data = json.load(jsonFile)

    data["d"] = [str("fourth letter")]

    jsonFile.seek(0)
    json.dump(data, jsonFile)
    jsonFile.truncate()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.