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()
Related
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)
I am trying to create JSON file using python code. file is created successfully with English language but not properly working with Marathi Language.
Please check out code:
import os
import json
jsonFilePath = "E:/file/"
captchaImgLocation = "E:/file/captchaimg/"
path_to_tesseract = r"C:/Program Files/Tesseract-OCR/tesseract.exe"
image_path = r"E:/file/captchaimg/captcha.png"
x = {
"FName": "प्रवीण",
}
# convert into JSON:
y = json.dumps(x, ensure_ascii=False).encode('utf8')
# the result is a JSON string:
print(y.decode())
completeName = os.path.join(jsonFilePath, "searchResult_Unicode.json")
print(str(completeName))
file1 = open(completeName, "w")
file1.write(str(y))
file1.close()
O/P on console:
{"FName": "प्रवीण"}
<br>
File created inside folder like this:
b'{"FName": "\xe0\xa4\xaa\xe0\xa5\x8d\xe0\xa4\xb0\xe0\xa4\xb5\xe0\xa5\x80\xe0\xa4\xa3"}'
There is no run time or compile time error but JSON is created with with above format.
Please suggest me any solution.
Open the file in the encoding you need and then json.dump to it:
import os
import json
data = { "FName": "प्रवीण" }
# Writing human-readable. Note some text viewers on Windows required UTF-8 w/ BOM
# to *display* correctly. It's not a problem with writing, but you can use
# encoding='utf-8-sig' to hint to those programs that the file is UTF-8 if
# you see that issue. MUST use encoding='utf8' to read it back correctly.
with open('out.json', 'w', encoding='utf8') as f:
json.dump(data, f, ensure_ascii=False)
# Writing non-human-readable for non-ASCII, but others will have few
# problems reading it back into Python because all common encodings are ASCII-compatible.
# Using the default encoding this will work. I'm being explicit about encoding
# because it is good practice.
with open('out2.json', 'w', encoding='ascii') as f:
json.dump(data, f, ensure_ascii=True) # True is the default anyway
# reading either one is the same
with open('out.json', encoding='utf8') as f:
data2 = json.load(f)
with open('out2.json', encoding='utf8') as f: # UTF-8 is ASCII-compatible
data3 = json.load(f)
# Round-tripping test
print(data == data2, data2)
print(data == data3, data3)
Output:
True {'FName': 'प्रवीण'}
True {'FName': 'प्रवीण'}
out.json (UTF-8-encoded):
{"FName": "प्रवीण"}
out2.json (ASCII-encoded):
{"FName": "\u092a\u094d\u0930\u0935\u0940\u0923"}
You have encoded the JSON string, so you must either open the file in binary mode or decode the JSON before writing to file, so:
file1 = open(completeName, "wb")
file1.write(y)
or
file1 = open(completeName, "w")
file1.write(y.decode('utf-8'))
Doing
file1 = open(completeName, "w")
file1.write(str(y))
writes the string representation of the bytes to the file, which always the wrong thing to do.
Do you want your json to be human readable? It's usually bad practice since you would never know what encoding to use.
You can write/read your json files with the json module without worrying about encoding:
import json
json_path = "test.json"
x = {"FName": "प्रवीण"}
with open(json_path, "w") as outfile:
json.dump(x, outfile, indent=4)
with open(json_path, "r") as infile:
print(json.load(infile))
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.
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()
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)