How to create a manual diff between two Json objects which can be sent to Reviewboard using python?
-
14-07-2021 - |
Question
How do I create a diff of two json objects such that they are in the manual diff format which can be sent to reviewboard? I need to generate the diff from inside a python script.I think manual diffs are generated using the "diff file1 file2" command line utility. Can I generate a similar reviewboard compatible diff using difflib? Or is there another library that I need to use? Thanks!
Solution
Use difflib:
def show_diff(seqm):
output= []
for opcode, a0, a1, b0, b1 in seqm.get_opcodes():
if opcode == 'equal':
output.append(seqm.a[a0:a1])
elif opcode == 'insert':
output.append("<ins>" + seqm.b[b0:b1] + "</ins>")
elif opcode == 'delete':
output.append("<del>" + seqm.a[a0:a1] + "</del>")
elif opcode == 'replace':
output.append("<del>" + seqm.a[a0:a1] + "</del>" + "<ins>" + seqm.b[b0:b1] + "</ins>" )
else:
raise RuntimeError, "Unexpected opcode"
return ''.join(output)
In your situation, you compare your json files (I just used dummy text):
In [4]: sm = difflib.SequenceMatcher(None, 'hello', 'hello world')
In [6]: diff = show_diff(sm)
In [7]: diff
Out[7]: 'hello<ins> world</ins>'
Look at the documentation if you need a different output from difflib
OTHER TIPS
I just think before going through diff, you should reformat JSON object lets say on alphabetical and numeric order.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow