You can do this.
data[0]['f'] = var
Answer from Jayanth Koushik on Stack OverflowYou can do this.
data[0]['f'] = var
One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:
test_json = { "a": 1, "b": 2}
Once you do this, adding a json element only involves the following line:
test_json["c"] = 3
This will result in:
{'a': 1, 'b': 2, 'c': 3}
Afterwards, you can add that json back into an array or a list of that is desired.
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)
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)
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))
a dictionary needs to be added to a json file which is already created. how do i do so?
I would do this:
data["list"].append({'b':'2'})
so simply you are adding an object to the list that is present in "data"
Elements are added to list using append():
>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}
If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead:
>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}
After doing that, you can assemble JSON again from dictionary you modified:
>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'
jsobj["a"]["b"]["e"].append({"f":var3, "g":var4, "h":var5})
jsobj["a"]["b"]["e"].append({"f":var6, "g":var7, "h":var8})
Just add the dictionary as a dictionary object not a string :
jsobj["a"]["b"]["e"].append(dict(f=var3))
Full source :
var1 = 11
var2 = 32
jsonobj = {"a":{"b":{"c": var1,
"d": var2,
"e": [],
},
},
}
var3 = 444
jsonobj["a"]["b"]["e"].append(dict(f=var3))
jsonobj will contain :
{'a': {'b': {'c': 11, 'd': 32, 'e': [{'f': 444}]}}}
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))
The assignment statement x = y = z implies that both x and y will take on the value of z.
As an example, look at the byte code for the assignment a = b = 2:
In [45]: import dis; dis.dis(compile('a = b = 2', '', 'exec'))
1 0 LOAD_CONST 0 (2)
3 DUP_TOP
4 STORE_NAME 0 (a)
7 STORE_NAME 1 (b)
10 LOAD_CONST 1 (None)
13 RETURN_VALUE
With 4 STORE_NAME, a is assigned first to 2, followed by 7 STORE_NAME where b is then assigned to the same value, 2.
So, with
sal = json.loads(salaries)["Hritik"] = 0
sal receives the value 0. Also, a temporary variable is created when you call json.loads and that is modified, following which the reference is lost.
In order to get this to work, you'll need to break this up into 2 parts, as you have already done.
sal = json.loads(salaries)
sal['Hritik'] = 0
Why can't I append to the dict returned by json.loads inline as I can do with the dict sal ?
You can, and you do, but then you just discard that dict. It doesn't have any effect on the salaries variable, and you didn't assign the dict to sal. You assigned 0 to sal.
When you assign sal = json.loads(salaries), that makes a new dict, unrelated to the first dict, and then you actually assign the new dict to sal. Modifications to this new dict are still visible when you view the dict through sal.