-1

I have JSON file with the following structure:
{'1234': 'ABC', '2345': 'BCD', '3456': 'CDE'}

I want to append the key value pair : {'4567': 'DEF'} to this JSON file so that it looks like:
{'1234': 'ABC', '2345': 'BCD', '3456': 'CDE', '4567': 'DEF'}

This is the code I have but it adds the key: value pair as another dictionary like structure:

new_data = {'4567': 'DEF}
j = json.dumps(new_data)
with open('hashDir.json','r+') as file:
       file.write(j)
       file.close()
martineau
  • 119,623
  • 25
  • 170
  • 301
PBLead
  • 3
  • 3
  • update "r+" to "w+" in line 3 as r stands for read ,w for write – gowridev May 30 '21 at 18:20
  • Duplicate https://stackoverflow.com/questions/23111625/how-to-add-a-key-value-to-json-data-retrieved-from-a-file-with-python – mohammed wazeem May 30 '21 at 18:28
  • @gowridev: "r+" allows writing. – martineau May 30 '21 at 18:31
  • my mistake, i didn't check the mode.
    r+ : Opens a file for reading and writing, placing the pointer at the beginning of the file. w : Opens in write-only mode. The pointer is placed at the beginning of the file and this will overwrite any existing file with the same name. It will create a new file if one with the same name doesn't exist.
    – gowridev May 31 '21 at 01:55

2 Answers2

0
import json

new_data = {'4567': 'DEF'}

with open("hashDir.json", "r+") as file:
    data = json.load(file)
    data.update(new_data)
    file.seek(0)
    json.dump(data, file)
Sudipto
  • 299
  • 2
  • 11
  • This allowed me to append the new key: value pair but one of the already existing pair in the json file got deleted. – PBLead May 30 '21 at 18:56
  • this would only happen if you have the same key in both new data and existing JSON files. For example, your new data has a key-value like `"mykey": 'new value'` and your JSON file already contained `"mykey": 'my old value'` in this case after updating the JSON file your old value will be replaced. It is not possible to keep the same key more than once in JSON / dictionary in python – Sudipto May 31 '21 at 02:40
0

Sudipto's solution is short and sweet, assuming you want to modify the original file. Just in case you don't, or if you want to separate reading and writing for whatever reason, here's a slightly different option:

import json

with open('hashDir.json', 'r') as f:
  json_dict = json.load(f)

new_data = {"4567": "DEF"}
json_dict.update(new_data)

with open('hashDir.json', 'w') as f:
  f.write(json.dumps(json_dict))

...this is assuming that you have only a very light file such as the one you described above. Of course, if you just want to replace the original file you could use Sudipto's solution, or you could give the file the same name in the second with.

Vicks
  • 141
  • 2
  • 8