How can I test whether two JSON objects are equal in python, disregarding the order of lists?

例如

JSON文档a:

{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}

JSON document b:

{
    "success": false,
    "errors": [
        {"error": "required", "field": "name"},
        {"error": "invalid", "field": "email"}
    ]
}

a and b should compare equal, even though the order of the "errors" lists are different.

推荐答案

If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a and b:

import json

a = json.loads("""
{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}
""")

b = json.loads("""
{
    "success": false,
    "errors": [
        {"error": "required", "field": "name"},
        {"error": "invalid", "field": "email"}
    ]
}
""")
>>> sorted(a.items()) == sorted(b.items())
False

... but that doesn't work, because in each case, the "errors" item of the top-level dict is a list with the same elements in a different order, and sorted() doesn't try to sort anything except the "top" level of an iterable.

To fix that, we can define an ordered function which will recursively sort any lists it finds (and convert dictionaries to lists of (key, value) pairs so that they're orderable):

def ordered(obj):
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    else:
        return obj

If we apply this function to a and b, the results compare equal:

>>> ordered(a) == ordered(b)
True

Json相关问答推荐

从Razor Pages的AJAX Json呈现DataTables问题.Net GET

盒子图显示不正确

Postgres Select json数组并重新映射属性名称

简单条形图和有序分类中条形图的 colored颜色 梯度

JSONPath:查找子项目条件在字符串列表中的项目

如何在 wso2 中组合 2 个 json 有效负载?

如何在 Django 的模板语言中获取 json 键和值?

Jackson 的@JsonView、@JsonFilter 和 Spring

使用 @ResponseBody 自定义 HttpMessageConverter 来做 Json 事情

如何使用 json.net 将数据表转换为 json 字符串?

从多维数组数据生成json字符串

如何从Typescript 中的json响应中获取日期对象

如何在 json 编码字符串内的子数组数据周围添加方括号?

jQuery循环.each()JSON键/值不起作用

PostgreSQL 中的 JSON 模式验证?

使用 Python 3 读取 JSON 文件

AJAX 将 JavaScript 字符串数组发布到 JsonResult 作为 List 总是返回 Null?

从 JSON 到 JSONL 的 Python 转换

为什么 jqXHR.responseText 返回字符串而不是 JSON 对象?

不处理从这里抛出的错误