Assuming you have a test.json file with the following content:
{"67790": {"1": {"kwh": 319.4}}}
Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:
import json
a_dict = {'new_key': 'new_value'}
with open('test.json') as f:
data = json.load(f)
data.update(a_dict)
with open('test.json', 'w') as f:
json.dump(data, f)
Then, in test.json, you'll have:
{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}
Hope this is what you wanted.
Answer from alecxe on Stack OverflowAssuming you have a test.json file with the following content:
{"67790": {"1": {"kwh": 319.4}}}
Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:
import json
a_dict = {'new_key': 'new_value'}
with open('test.json') as f:
data = json.load(f)
data.update(a_dict)
with open('test.json', 'w') as f:
json.dump(data, f)
Then, in test.json, you'll have:
{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}
Hope this is what you wanted.
You need to update the output of json.load with a_dict and then dump the result.
And you cannot append to the file but you need to overwrite it.
Videos
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)json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it.
Fortunately, there are lots of other options. A particularly simple one is CSV; which is supported well by python's standard library. The biggest downside is that it only works well for text; it requires additional action on the part of the programmer to convert the values to numbers or other formats, if needed.
Another option which does not have this limitation is to use a sqlite database, which also has built-in support in python. This would probably be a bigger departure from the code you already have, but it more naturally supports the 'modify a little bit' model you are apparently trying to build.
You probably want to use a JSON list instead of a dictionary as the toplevel element.
So, initialize the file with an empty list:
with open(DATA_FILENAME, mode='w', encoding='utf-8') as f:
json.dump([], f)
Then, you can append new entries to this list:
with open(DATA_FILENAME, mode='w', encoding='utf-8') as feedsjson:
entry = {'name': args.name, 'url': args.url}
feeds.append(entry)
json.dump(feeds, feedsjson)
Note that this will be slow to execute because you will rewrite the full contents of the file every time you call add. If you are calling it in a loop, consider adding all the feeds to a list in advance, then writing the list out in one go.
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"}]}'
First read the data from the file.
with open('data2.txt') as data_file:
old_data = json.load(data_file)
Then append your data to the old data
data = old_data + data
Then rewrite the whole file.
with open('data2.txt', 'w') as outfile:
json.dump(data, outfile)
This is probably not the most Pythonic way to handle your request but I hope it will help with some issues you might encounter. I wrapped the loading and dumping into try-except bracelets to make the code more robust. The biggest surprise for myself was that you don't use 'a' when opening the file as output file but 'w' instead. However,this makes perfect sense if you consider that you append already in line "data.append(data1)", so there is no need to append twice when dumping to the file.
data = [{"username": "Mike", "code": "12345", "city": "NYC"}]
data1 = {"username": "Kelly", "code": "56789", "city": "NYC"}
data2 = {"username": "Bob", "code": "12222", "city": "NYC"}
try:
with open('append.txt', 'r') as fin:
data = json.load(fin)
except FileNotFoundError as exc:
pass
try:
if data:
data.append(data1)
with open('append.txt', 'w') as fout:
json.dump(data, fout)
except UnboundLocalError as exc:
with open('append.txt', 'w') as fout:
json.dump(data, fout)
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}]}}}
def write(filename, new_data): # function that appends data to the specified file
with open(filename, "r") as file1:
data = json.load(file1)
data.append(new_data)
with open(filename, "w") as file1:
# Sets file's current position at offset.
file1.seek(0)
json.dump(data, file1, indent=4)I have this function that appends objects exactly how I want; however, it only does it to the bottom of the file rather than the top.