【问题标题】:how to compare 2 json in python [closed]如何在python中比较2个json [关闭]
【发布时间】:2012-06-23 21:26:32
【问题描述】:

如何在python中比较2个json对象下面是示例json。

sample_json1={
    {
       "globalControlId": 72,
       "value": 0,
       "controlId": 2
   },
   {
       "globalControlId": 77,
       "value": 3,
       "controlId": 7
   }
}

sample_json2={
    {
       "globalControlId": 72,
       "value": 0,
       "controlId": 2
   },
   {
       "globalControlId": 77,
       "value": 3,
       "controlId": 7
   }
}

【问题讨论】:

  • 你能解释一下为什么if sample_json1 == sample_json2:不够用吗???
  • 您编写的“json”示例无效。如果您需要任何帮助,您必须向我们提供更多上下文/工作代码。

标签: python


【解决方案1】:

似乎通常的比较工作正常

import json
x = json.loads("""[
    {
       "globalControlId": 72,
       "value": 0,
       "controlId": 2
   },
   {
       "globalControlId": 77,
       "value": 3,
       "controlId": 7
   }
]""")

y = json.loads("""[{"value": 0, "globalControlId": 72,"controlId": 2}, {"globalControlId": 77, "value": 3, "controlId": 7 }]""")

x == y # result: True    

【讨论】:

    【解决方案2】:

    这些不是有效的 JSON / Python 对象,因为数组 / 列表字面量在 [] 而不是 {} 内:

    UPDATE:比较字典列表(对象的序列化JSON数组),同时忽略列表项的顺序,列表需要排序或转换为集合

    sample_json1=[{"globalControlId": 72, "value": 0, "controlId": 2},
                  {"globalControlId": 77, "value": 3, "controlId": 7}]
    sample_json2=[{"globalControlId": 77, "value": 3, "controlId": 7},
                  {"globalControlId": 77, "value": 3, "controlId": 7}, # duplicity
                  {"globalControlId": 72, "value": 0, "controlId": 2}]
    
    # dictionaries are unhashable, let's convert to strings for sorting
    sorted_1 = sorted([repr(x) for x in sample_json1])
    sorted_2 = sorted([repr(x) for x in sample_json2])
    print(sorted_1 == sorted_2)
    
    # in case the dictionaries are all unique or you don't care about duplicities,
    # sets should be faster than sorting
    set_1 = set(repr(x) for x in sample_json1)
    set_2 = set(repr(x) for x in sample_json2)
    print(set_1 == set_2)
    

    【讨论】:

    • 如果订单更改以下示例的示例失败,这将不起作用
    • sample_json1=[{"globalControlId": 72, "value": 0, "controlId": 2}, {"globalControlId": 77, "value": 3, "controlId": 7} ] sample_json2=[ {"globalControlId": 77, "value": 3, "controlId": 7}, {"globalControlId": 72, "value": 0, "controlId": 2}]
    • 比较应该成功,即使订单发生变化,请在这里帮助我
    • 根据cmets更新
    • @zochhuana 其他解决方案是否处理嵌套的 json?即使确实如此,我也不会指望它..如果您需要进行深入比较,谷歌的顶级链接之一是Deep Equality Test for Nested Python Structures
    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多