I have a python script where I am updating a json file with some of the key values to a particular value, but whenever I update the json file and try to write it to a different blank json file by using this:
I’m not sure what you’re doing. The normal way to change the data is to do something like this:
# Read the data.
with open(json_path, encoding="utf-8") as file:
data = json.load(file)
# Change the data.
...
# Write the data.
with open(new_json_path, "w", encoding="utf-8") as file:
json.dump(data, file)
# This is what I am trying to do
file1_json_path = '/Users/***/Desktop/testpr/file1.json'
file2_json_edited_path = '/Users/***/Desktop/testpr/testpr1/file2.json'
version1 = "8.4.0.9"
version2 = "8.4"
json_content = ""
replaced_content = ""
#clone the file
dest = shutil.copy(file1_json_path, file2_json_edited_path)
print("========FILEISNOWCOPIED==========")
#read the file
with open(file2_json_edited_path, encoding="utf-8") as jsonfile:
json_content = json.dumps(jsonfile.read())
replaced_content = json_content.replace(version2, version1)
print("*******************the replaced content is************************* " + str(replaced_content))
#writing the content back to the new file
with open(file2_json_edited_path, 'w', encoding="utf-8") as file:
file.write(json.loads(json.dumps(replaced_content.replace("\\n", ""))))
file.close()
Seems you could replace all of this after version2 = "8.4" with:
with open(file1_json_path, "r") as in_file:
with open(file2_json_edited_path, "w") as out_file:
out_file.write(in_file.read().replace(version2, version1))
There’s no need to copy the file before modifying it, and there’s no need to parse the JSON if you just want to modify the raw text.
Actually looks like there is one more thing that needs to get done here, I need to make sure the new file has all values replaced but not one.
for example: if in_file a json tag called is find I don’t want to replace that, but replace all others, what is the best way to get away with this?
Okay, if you don’t want a global string replacement, then you probably do want to parse and dump JSON, so that you can modify the contents as a dictionary before writing them to the new file. Here you would do something like:
with open(file1_json_path, "r") as in_file:
struct = json.load(in_file)
# struct is a dictionary, modify it in place
struct['key1']['key2']['version'] = version2
with open(file2_json_edited_path, "w") as out_file:
json.dump(struct, out_file)