比较两个JSON对象,无论它们中元素的顺序如何 [英] Comparing two JSON objects irrespective of the sequence of elements in them

查看:101
本文介绍了比较两个JSON对象,无论它们中元素的顺序如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python中是否有任何方法/类/模块比较两个json对象并打印更改/差异?

Is there any way / class / module in python to compare two json objects and print the changes/differences?

我尝试使用"json_tools"给出了很好的结果,但是在两个json对象中存在顺序不同的python列表的情况下,diff失败.

I have tried with "json_tools" which is gives fairly good results, however diff failed in case if there are python lists' with elements in different orders in two json objects.

例如

{
    'Person' : 
        {
            'FName'    : 'John',
            'LName'    : 'Rambo',
            'Sex'      : 'Male'
            'Height'   : '6 ft',
            'Weight'   : '90 KG',
            'Children' :
                [
                    {
                        'FName'  : 'Anna',
                        'LName'  : 'Rambo',
                        'Sex'    : 'Female',
                        'Height' : '5 ft',
                        'Weight' : '55 KG',
                    },
                    {
                        'FName'  : 'Jemmy',
                        'LName'  : 'Rambo',
                        'Sex'    : 'Male',
                        'Height' : '5 ft',
                        'Weight' : '60 KG',
                    }

                ]
        }
}

JSON 2:

{
    'Person' : 
        {
            'FName'    : 'John',
            'LName'    : 'Rambo',
            'Sex'      : 'Male'
            'Height'   : '6 ft',
            'Weight'   : '90 KG',
            'Children' :
                [
                    {
                        'FName'  : 'Jemmy',
                        'LName'  : 'Rambo',
                        'Sex'    : 'Male',
                        'Height' : '5 ft',
                        'Weight' : '60 KG',
                    },
                    {
                        'FName'  : 'Anna',
                        'LName'  : 'Rambo',
                        'Sex'    : 'Female',
                        'Height' : '5 ft',
                        'Weight' : '55 KG',
                    }
                ]
        }
}

json差异显示两个json不匹配.逻辑上它们是相同的.

json diff shows the Two jsons are mismatched.. Logically those are identical..

在python中是否存在json匹配和比较的好方法?

Is there a good way of json matching and comparing in python?

推荐答案

您可以使用 jsondiff

from jsondiff import diff
diff(json1, json2)

......假设您已从示例中加载了json条目的json1和json2(顺便说一句,在"sex"条目之后您缺少逗号).

... assuming you have json1 and json2 loaded with the json entries from your example (and by the way, you have a missing comma after the 'sex' entry).

这篇关于比较两个JSON对象,无论它们中元素的顺序如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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