Python code opening json file - more optimal - python

How could I write this piece of code more optimal, not to have repetition? So, first I'm checking if there's a .json file, if there isn't I make it. If there is, I first open it, update it with new data, and then write in it again.
if not os.path.exists(json_path):
with open(json_path, "w") as json_file:
json.dump(my_dict, json_file)
else:
with open(json_path) as json_file:
data = json.load(json_file)
data.update(my_dict)
with open(json_path, 'w') as json__file:
json.dump(data, json__file)

I think you can invert your condition to read the file first. Then later write to the file because you always end up writing.
if os.path.exists(json_path):
with open(json_path) as json_file:
data = json.load(json_file)
data.update(my_dict)
my_dict = data
with open(json_path, "w") as json_file:
json.dump(my_dict, json_file)

Related

Updating value of a key in JSON with Python

I am trying to change a value of only a key but as a result my whole json data is appended to old one.
Here is the script
import json
with open('test.json', "r+") as json_file:
wifi = json.load(json_file)
status = wifi["wifi_status"]
wifi["wifi_status"] = "off"
json.dump(wifi, json_file)
and this is the json file
{"wifi_status":"on","ssid":"my_router","pw":"my_password"}
and the result
{"wifi_status":"on","ssid":"my_router","pw":"my_password"}{"wifi_status": "off", "ssid": "my_router", "pw": "my_password"}
Is there a way to modify a value without dumping all information?
You open the file in r+ You must open in w to overwrite the file
import json
with open('test.json', "r+") as json_file:
wifi = json.load(json_file)
status = wifi["wifi_status"]
wifi["wifi_status"] = "off"
with open('test.json', "w") as json_file:
json.dump(wifi, json_file)
The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.
import json
with open("x.json", "r+") as jsonFile:
wifi = json.load(jsonFile)
wifi["wifi_status"] = "off"
with open("x.json", "w") as jsonFile:
json.dump(wifi, jsonFile)
Alternatively, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous.
json.dumps is appending to the end of the cursor of the file pointer.
You can re-open the file with w+ to clear all the contents of the file, or you can put json_file.seek(0) before json.dumps to bring the cursor back to the start.
You can try this
import json
jsonFile = open("test.json", mode="r")
jdata = json.load(jsonFile)
jdata["wifi_status"] = "off"
jsonFile.close()
jsonFile = open('test.json', mode='w+')
json.dump(jdata, jsonFile)
jsonFile.close()

Update a JSON file with Python and keep the original format

I have a Python script that updates some value of a JSON file, and the original format of my JSON looks like:
To edit the value I use this code:
import json
status_wifi = "ok"
with open("config_wifi.json", "r") as jsonFile:
data = json.load(jsonFile)
data['wifi_session']['status'] = status_wifi
with open("config_wifi.json", "w") as jsonFile:
json.dump(data, jsonFile)
But when the values are updated, the format of my JSON is compressed like this:
I want the JSON file to keep its original format with all spaces and line breaks. How could I do that?
Try json.dumps(json_obj, indent=4)
Example:
import json
status_wifi = "ok"
with open("config_wifi.json", "r") as jsonFile:
data = json.load(jsonFile)
data['wifi_session']['status'] = status_wifi
with open("config_wifi.json", "w") as jsonFile:
json.dump(json.dumps(data, indent=4), jsonFile)
The indent is the number of spaces for a tab.
If you set this parameter, the JSON will be formatted.
You can read more about it here.

No JSON object could be decoded ,even when valid json in present in the file

For converting dictionary element to Json and write to a file ,
with open(filename,'w') as f:
if(os.stat(f).st_size == 0):
json.dump(new_data, f)
else:
data = json.load(f)
data.update(new_data)#adding a new dictionary
json.dump(data, f)
i am able to write only one json to the file. When i want to read the exisiting file and then append another set of dictionary , i am unable to do .
Getting ValueError: No JSON object could be decoded tried
json.loads(f), json.load(f)
You should simply read from the file first, if it exists. If it is already empty, or contains invalid JSON, or doesn't exist, initialize data to the empty dict (which is the identity element for the update method).
try:
with open(filename) as f:
data = json.load(f)
except (IOError, ValueError):
data = {}
Then open the file in write mode to write the updated data.
data.update(new_data)
with open(filename, 'w') as f:
json.dump(data, f)

How to update a JSON file by using Python?

I am using Python and I have a JSON file in which I would like to update a value related to a given key. That is, I have the my_file.json containing the following data
{"a": "1", "b": "2", "c": "3"}
and I would like to just change the value related to the b key from 2 to 9 so that the updated file look as like:
{"a": "1", "b": "9", "c": "3"}
How can I make that?
I tried the following but without success (the changes are not saved to the file):
with open('my_file.json', 'r+') as f:
json_data = json.load(f)
json_data['b'] = "9"
f.close()
You did not save the changed data at all. You have to first load, then modify, and only then save. It is not possible to modify JSON files in-place.
with open('my_file.json', 'r') as f:
json_data = json.load(f)
json_data['b'] = "9"
with open('my_file.json', 'w') as f:
f.write(json.dumps(json_data))
You may also do this:
with open('my_file.json', 'r+') as f:
json_data = json.load(f)
json_data['b'] = "9"
f.seek(0)
f.write(json.dumps(json_data))
f.truncate()
If you want to make it safe, you first write the new data into a temporary file in the same folder, and then rename the temporary file onto the original file. That way you will not lose any data even if something happens in between.
If you come to think of that, JSON data is very difficult to change in-place, as the data length is not fixed, and the changes may be quite significant.
You are almost there, you only have to write the updated json_data back to the file. Get rid of f.close(), as the with statement will ensure that the file is closed. Then, issue
with open('my_file.json', 'w') as f:
f.write(json.dumps(json_data))
This is simplest way to do the json file updation/writing.
where you are creating instance of json file as 'f' and the writing the 'data' into the json file,
#write json file
with open('data.json', 'w') as f:
json.dump(data, f)
#Read json file
with open('data.json', 'r') as f:
json.load(data, f)
Open the file and store in one variable all the content using json.load function
Update your key stored in the previous variable
Open the file another time and update your content with the variable updated
def updateJsonFile():
jsonFile = open("my_file.json", "r") # Open the JSON file for reading
data = json.load(jsonFile) # Read the JSON into the buffer
jsonFile.close() # Close the JSON file
## Working with buffered content
data["b"] = "9"
## Save our changes to JSON file
jsonFile = open("my_file.json", "w+")
jsonFile.write(json.dump(data))
jsonFile.close()

How to append to a JSON file in Python?

I have the a JSON file which contains {"67790": {"1": {"kwh": 319.4}}}. Now I create a dictionary a_dict which I need to append to the JSON file.
I tried this code:
with open(DATA_FILENAME, 'a') as f:
json_obj = json.dump(a_dict, json.load(f)
f.write(json_obj)
f.close()
What is wrong with the code? How can I fix the problem?
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.
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.
json_obj=json.dumps(a_dict, ensure_ascii=False)

Categories