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 Answers1

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()
skulden
  • 380
  • 1
  • 10