Issue
Using python I'm trying to diff two json files, update if there's a difference.
I have a rough draft going but haven't found out how to update my file!
import json
import sys
import jsondiff as jd
from jsondiff import diff
one="$1"
two="$2"
def compare_json(one, two) :
with open(one, "r") as f, open(two, "r") as f2:
file_one=json.load(f)
file_two=json.load(f2)
differences = diff(file_one, file_two, syntax='explicit')
print(differences)
update = differences[jd.update]
print(update)
insert = differences[jd.insert]
print(insert)
delete = differences[jd.delete]
print(delete)
if __name__ == "__main__":
compare_json(sys.argv[1],sys.argv[2])
I can get the differences but I haven't figure out a good way in updating the file.
My end goal is this:
diffy = diff(file_one,file_two)
if diffy
update file_two
I only want to update values that are different in file two.
For example:
file one:
{ "type": "secure"
"secure": {
"id": "123",
"client": "google"
}
}
file two:
{ "type": "secure"
"secure": {
"id": "456",
"client": "google"
}
}
So the only difference between the files is the value of secure["id"]. I would like to update the value of secure["id"] in file two to the value of secure["id"] in file one. (Basically making file one equal to file two without rewriting everything in the file)
Any suggestions how to do this cleanly?
Solution
Sorry for the late response.. deadlines at work...
I ended up going with jsondiff
Here's a sample code snippet (without any exception handling):
import jsondiff as jd
from jsondiff import diff
# open and load files
with open(one, "r") as f, open(two, "r") as f2:
file_one = json.load(f)
file_two = json.load(f2)
# get differences in file_two (file_one being the master)
differences = (file_two, file_one)
# in order to access $update from differences use jd.update
update = differences[jd.update]
# assuming there are updates, loop through and update them accordingly
for x in update:
file_two.update({x : update[x]})
# Open a new file and write the updated contents of file_two
outfile = open(outfile, "w")
json.dump(file_two, outfile, indent=4)
Turns out it wasn't too bad once using jsondiff
and understanding how to access the objects returned
Answered By - Stacker
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.