Python比较2个具有可变键和值长度的json

2024-04-27 03:25:35 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试将2个JSON与可变字段长度进行比较

到目前为止,我们有以下代码,正在进行diff样式的JSON比较:

def diffjson(found, expected):
    '''diff two json strings'''
    found = found.split()
    expected = expected.split()
    return difflist(
        found,
        expected,
        fromfile="found",
        tofile="expected",
        rstrip=True)

def difflist( fromlines, tolines, fromfile=None, tofile=None, quiet=False, addnl=None, rstrip=False ) :
    if rstrip :
        fromlines  = [ x.rstrip() for x in fromlines  if x != '' ]
        tolines    = [ x.rstrip() for x in tolines    if x != '' ]
    diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, n=5)
    diff = list(diff)
    if len(diff) :
        if not quiet :
            if addnl :
                for x in diff :
                    ret = ret + (x)
                    ret = ret + (addnl)
            else :
                ret = diff
        return ret
    else :
        return True

从潘多基亚借来的

例如,输出为:

\--- found +++ expected @@ -3364,11 +3364,11 @@ group global access"]},
"vjafUGJ9H0": {"260":-["test",+["us-east-1", null, "Not enabled", null, null, 

所以这意味着第一个JSON与另一个JSON的值“test”不同

我的问题是:

有没有一种不同的方法来比较JSON和可变的键和值长度

比较:

{"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "0.0.0.0/0"]}}

使用:

{"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "Blue", "0.0.0.0/0"]}}

谢谢你


Tags: nonejsonforreturnifdiffexpectedret