+ 1
editing a dictionary in a json file
When using the json library in Python, is it possible to add a new key:value pair to an already existing dictionary in a json file? I'm asking because any dictionary stored in a json file doesn't have a variable name, so it seems impossible to edit a particular one, I've only been able to add a new dictionary after the one I want to edit.
7 Answers
+ 3
import json with open('data.json', 'w') as fp:
json.dump(data, fp)
Supply extra arguments like `sort_keys` or `indent` to get a pretty result. The argument *sort_keys* will sort the keys alphabetically and *indent* will indent your data structure with `indent=N` spaces.
0
I don't see how this allows me to add a new 'key:value' pair to an already existing dictionary in a json file
0
see this. should help!
http://www.diveintopython3.net/serializing.html#json-dump
0
as I see it, you just open the json file in a simple text editor, like Notepad and add a pair
"new_key": value
0
I can't do it manually through a text editor cause I'm trying to compile a code that automatically puts a user input into an already existing dictionary in a json file, so that the dictionary can be worked on as a whole unit.
0
OK. in that case there are two ways:
1)load json file, amend the dictionary, and dump back (as new json foile);
2)read a few lines of json file, add new pair, write new file pretending it is json (without actually using json module). that can be done by any other code, not necessary Python or JS
0
Yh thanks a lot.
I just realized I can write a code to store the inputs in a txt file and write a code to store the contents of txt file in a json file