当前位置: 首页 > 工具软件 > JSON Patch > 使用案例 >

python常见的json对象对比方法(deepdiff、json_tools、jsonpatch)

赫连昕
2023-12-01

  对比两个json对象差异,常见的第三方对比库deepdiff、json_tools、jsonpatch都能够满足我们的需求。

  用法:

  • deepdiff

    from deepdiff import DeepDiff
    
    a = {"name": "yanan", "pro": {"sh": "shandong", "city": ["zibo", "weifang"]}}
    b = {"name": "Yanan", "pro": {"sh": "shandong", "town": ["taian", "weifang"]}}
    
    result = DeepDiff(a, b)
    
    print(result)
    
    {'dictionary_item_added': [root['pro']['town']], 'dictionary_item_removed': [root['pro']['city']], 'values_changed': {"root['name']": {'new_value': 'Yanan', 'old_value': 'yanan'}}}
    
  • json_tools

    import json_tools
    
    a = {"name": "yanan", "pro": {"sh": "shandong", "city": ["zibo", "weifang"]}}
    b = {"name": "Yanan", "pro": {"sh": "shandong", "town": ["taian", "weifang"]}}
    
    result = json_tools.diff(a, b)
    
    print(result)
    
    [{'replace': '/name', 'value': 'Yanan', 'prev': 'yanan'}, {'remove': '/pro/city', 'prev': ['zibo', 'weifang']}, {'add': '/pro/town', 'value': ['taian', 'weifang']}]
    
  • jsonpatch

    import jsonpatch
    
    a = {"name": "yanan", "pro": {"sh": "shandong", "city": ["zibo", "weifang"]}}
    b = {"name": "Yanan", "pro": {"sh": "shandong", "town": ["taian", "weifang"]}}
    
    result = jsonpatch.JsonPatch.from_diff(a, b)
    print(result)
    

    输出结果:

    [{"op": "remove", "path": "/pro/city"}, {"op": "add", "path": "/pro/town", "value": ["taian", "weifang"]}, {"op": "replace", "path": "/name", "value": "Yanan"}]
    

  但无论哪种方法,都不方便我们根据对比结果,进行修改原始数据。

 类似资料: