I'm trying to get json diff using difflib.unified_diff
but the out seems to be wrong.
from difflib import unified_diff
import sys
sone = """
{
"one": 1,
"a": "A",
"b": "B"
}
"""
stwo = """
{
"two": 2,
"a": "A",
"b": "B"
}
"""
for line in unified_diff(sone, stwo, fromfile="one", tofile="two", lineterm='\n'):
sys.stdout.write(line)
And the output looks like below,
--- one
+++ two
@@ -6,13 +6,13 @@
"+t+w o-n-e " : -1+2
Where I should be getting something like below,
@@ -1,5 +1,5 @@
{
- "one": 1,
+ "two": 2,
"a": "A",
"b": "B"
}
I'm using Python 2.7.14 :: Anaconda custom (64-bit) I think I'm doing something silly
The output is correct. The first two inputs to unified_diff
are normally iterators of strings, as if you read in from fp.readlines()
.
Because you only give a single sting, it is treating it as if it is the only string from the iterator. In other words, it is treating it as one long string (which it is), and not a separate lines from a file.
To get the output your expect, you need to split the multiline strings on the linebreak.
for line in unified_diff(sone.split('\n'), stwo.split('\n')):
print(line)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.