Sounds like you want to load a dictionary from json, add new key values and write it back. If that's the case, you can do this:
with open('python_dictionary.json','r+') as f:
dic = json.load(f)
dic.update(new_dictionary)
json.dump(dic, f)
(mode is 'r+' for reading and writing, not appending because you're re-writing the entire file)
If you want to do the append thing, along with json.dumps, I guess you'd have to remove the first { from the json.dumps string before appending. Something like:
with open('python_dictionary.json','a') as f:
str = json.dumps(new_dictionary).replace('{', ',', 1)
f.seek(-2,2)
f.write(str)
Answer from Munick on Stack OverflowSounds like you want to load a dictionary from json, add new key values and write it back. If that's the case, you can do this:
with open('python_dictionary.json','r+') as f:
dic = json.load(f)
dic.update(new_dictionary)
json.dump(dic, f)
(mode is 'r+' for reading and writing, not appending because you're re-writing the entire file)
If you want to do the append thing, along with json.dumps, I guess you'd have to remove the first { from the json.dumps string before appending. Something like:
with open('python_dictionary.json','a') as f:
str = json.dumps(new_dictionary).replace('{', ',', 1)
f.seek(-2,2)
f.write(str)
When the 'r+' or 'a' option does not work properly, you can do the following:
with open('python_dictionary.json','r') as f:
dic = json.load(f)
dic.update(new_dictionary)
with open('python_dictionary.json','w') as f:
json.dump(dic, f)
The first part read the existing dictionary. Then you update the dictionary with the new dictionary. Finally, you rewriting the whole updated dictionary.
Hello I currently learning json in python i want to append a dictionary in a json file ontop of existing ones but every time i do this i get this error in VS-Code:
End of file expected.
Can somebody help me?
Here is the Code:
dict = {
"data1" : data3,
"data2" : data4
}
data = json.dumps(dict)
with open("index.json" , "a") as file:
json.dump(data , file)
python - How to add new dictionary into existed json file with dictionary? - Stack Overflow
json - Python: add to a dictionary in a list - Stack Overflow
Python, add dictionary to JSON file - Stack Overflow
how to add a dicitionary to a json file. pls help coz im not able to find a good answers in stack overflow or gfg
Videos
There are several questions here. The main points worth mentioning:
- Use can use a
listto hold your arguments and use*argsto unpack when you supply them toadd_entry. - To check / avoid duplicates, you can use
setto track items already added. - For writing to JSON, now you have a list, you can simply iterate your list and write in one function at the end.
Putting these aspects together:
import json
res = []
seen = set()
def add_entry(res, name, element, type):
# check if in seen set
if (name, element, type) in seen:
return res
# add to seen set
seen.add(tuple([name, element, type]))
# append to results list
res.append({'name': name, 'element': element, 'type': type})
return res
args = ['xyz', '4444', 'test2']
res = add_entry(res, *args) # add entry - SUCCESS
res = add_entry(res, *args) # try to add again - FAIL
args2 = ['wxy', '3241', 'test3']
res = add_entry(res, *args2) # add another - SUCCESS
Result:
print(res)
[{'name': 'xyz', 'element': '4444', 'type': 'test2'},
{'name': 'wxy', 'element': '3241', 'type': 'test3'}]
Writing to JSON via a function:
def write_to_json(lst, fn):
with open(fn, 'a', encoding='utf-8') as file:
for item in lst:
x = json.dumps(item, indent=4)
file.write(x + '\n')
#export to JSON
write_to_json(res, 'elements.json')
you can try this way
import json
import hashlib
def add_entry(name, element, type):
return {hashlib.md5(name+element+type).hexdigest(): {"name": name, "element": element, "type": type}}
#add entry
entry = add_entry('xyz', '4444', 'test2')
#Update to JSON
with open('my_file.json', 'r') as f:
json_data = json.load(f)
print json_data.values() # View Previous entries
json_data.update(entry)
with open('elements.json', 'w') as f:
f.write(json.dumps(json_data))
You have to read your JSON file and then convert it to list instead of dict. Then you just need to append to that list and overwrite your JSON file.
import json
data = json.load(open('data.json'))
# convert data to list if not
if type(data) is dict:
data = [data]
# append new item to data lit
data.append({
"user": "user2",
"id": "21780"
})
# write list to file
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
You can do with the list not with the dict , try the below one solution if its help
import json
def appendList():
with open("test.json", mode='r', encoding='utf-8') as f:
feeds = json.load(f)
print(feeds)
with open("test.json", mode='w', encoding='utf-8') as feedsjson:
entry = { "user": "user3","id": "21574"}
feeds.append(entry)
print(json.dump(feeds, feedsjson))
But now I want to add a key/val pair to this dictionary
You can index the list and update that dictionary:
temp['logs'][0].update({'new_key': 'new_value'})
You can use this command to change your dict values :
>>> temp['logs'][0]={'no':'val'}
>>> temp
{'logs': [{'no': 'val'}]}
And this one to add values :
>>> temp['logs'][0].update({'yes':'val'})
>>> temp
{'logs': [{'key': 'val', 'yes': 'val'}]}
a dictionary needs to be added to a json file which is already created. how do i do so?