python中的多级JSON差异 [英] Multilevel JSON diff in python

查看:361
本文介绍了python中的多级JSON差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果已回答此问题,请链接我以作答, 我的问题是我想获取无序的多层json的差异.

Please link me to answer if this has already been answered, my problem is i want to get diff of multilevel json which is unordered.

x=json.loads('''[{"y":2,"x":1},{"x":3,"y":4}]''')
y=json.loads('''[{"x":1,"y":2},{"x":3,"y":4}]''')
z=json.loads('''[{"x":3,"y":4},{"x":1,"y":2}]''')

import json_tools as jt
import json_delta as jd


print jt.diff(y,z)
print jd.diff(y,z)
print y==z
print x==y

输出为

[{'prev': 2, 'value': 4, 'replace': u'/0/y'}, {'prev': 1, 'value': 3, 'replace': u'/0/x'}, {'prev': 4, 'value': 2, 'replace': u'/1/y'}, {'prev': 3, 'value': 1, 'replace': u'/1/x'}]
[[[2], {u'y': 2, u'x': 1}], [[0]]]
False
True

我的问题是如何使y和z相等,或者是否存在实际差异,具体取决于JSON的非顺序.

my question is how can i get y and z to be equal or if there are actual differences depending on non-order of the JSON.

种类繁多的词典列表,但我正在寻找一种能证明层次的东西,即列表/词典的列表/词典...

kind of unordered List of dictionaries but i am looking for something which is level-proof that is list/dict of dictionaries of list/dictionaries ...

推荐答案

使用以下函数部分解决了该问题

solved it partially with following function

def diff(prev,lat):
    p=prev
    l=lat


    prevDiff = []
    latDiff = []

    for d1 in p[:]:
        flag = False
        for d2 in l:
            if len(set(d1.items()) ^ set(d2.items())) == 0:
                p.remove(d1)
                l.remove(d2)
                flag = True
                break
        if not flag:
            prevDiff.append(d1)
            p.remove(d1)

    prevDiff = prevDiff + p
    latDiff = latDiff + l

    resJSONdata=[]
    if len(prevDiff) != 0:
        resJSONdata.append({'prevCount':len(prevDiff)})
        resJSONdata.append({'prev':prevDiff})
    if len(latDiff) != 0:
        resJSONdata.append({'latestCount':len(latDiff)})
        resJSONdata.append({'latest':latDiff})

#     return json.dumps(resJSONdata,indent = 4,sort_keys=True)
    return resJSONdata

它不是递归地逐级执行,但出于我的目的,这解决了问题

it's not doing it recursively into level into levels but for my purpose this solved the issue

这篇关于python中的多级JSON差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆