문제

i'm using a library to extrapolate the diffs between two json files. My code loads them into dictionaries and then uses datadiff to get the difference between the two data structure. The problem is that i want to process further the output of:

datadiff.diff

to make an html of the diffs found in the two data structures. In order to do it i have to process the output of the command and divide it in lines. Then if the lines begins with + i know that the output have to be referred to the second file compared, if the lines begins with - then i have to attribute it to the first file. Mycode:

    out = datadiff.diff(t[0].get("key"),t[1].get("key"))
    for line in out:
        if str(line).startswith("+"):
            f.write(str(line)+"<br/>")
        if str(line).startswith("-"):
            f.write(str(line)+"<br/>")

This code gices me a TypeError:

for line in out:
TypeError: 'DataDiff' object is not iterable

I can transform the whole datadiff.diff in a string but then i have to split it somehow to get all the lines as it get translated to a single line string:

         out = str(datadiff.diff(t[0].get("key"),t[1].get("key")))+"<br/>"

Datadiff Output:

diff in key:
--- a
+++ b
[
@@ -0,1 +0,1 @@
-{u'origin': u'NORMAL', u'score': 100, u'type': u'FEELINGS', u'name': u'sentiment negativo', u'children': [u'reato']},
 {u'origin': u'NORMAL', u'score': 100, u'type': u'FEELINGS', u'name': u'sentiment neg', u'children': [u'reato']},
+{u'origin': u'NORMAL', u'score': 50, u'type': u'FEELINGS', u'name': u'sentiment negativo', u'children': [u'reato']},
]
도움이 되었습니까?

해결책

You could take a look at the source for the DataDiff.stringify() method, where you can see how the output is generated from the .diffs list:

def output(ddiff, f, depth=0):
    for change, items in out.diffs:
        if change in ('insert', 'delete'):
            prefix = '-' if change == 'delete' else '+'
            for line in items:
                f.write('{}{}{}<br/>'.format(prefix, depth * ' ', line))
        elif change == 'datadiff':
            output(items, f, depth + 1)
            f.write(',')

output(out, f)

If you want to work with just the string output, then use str.splitlines() to get separate lines again:

for line in str(out).splitlines():
    # etc.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top