Python比较两个JSON文件内容是否相同

Python操作JSON文件

    • 题目分析
    • 比较方法1
    • 比较方法2
    • 测试文件

题目分析

  1. 操作JSON需要用到JSON包
  2. 把JSON文件转化为字典后进行比较
  3. 对比:普通比较“==”,现有的模块deepdiff

比较方法1

import json

"""
This snippet is used to compare two json files, and find out the differences.
"""
# read json file, return dict file
def file_reader(file_path):
    with open(file_path, 'rb') as json_file:
        file_contents = json.load(json_file)
        return file_contents

def dict_compare(d1, d2):
    d1_keys = set(d1.keys())
    d2_keys = set(d2.keys())
    shared_keys = d1_keys.intersection(d2_keys)
    added = d2_keys - d1_keys
    removed = d1_keys - d2_keys
    modified = {k: (d1[k], d2[k]) for k in shared_keys if d1[k] != d2[k]}
    same = set(k for k in shared_keys if d1[k] == d2[k])
    return added, removed, modified, same

if __name__ == "__main__":
    f1_path = './file1.json'
    f2_path = './file2.json'
    d1 = file_reader(f1_path)
    d2 = file_reader(f2_path)
    added, removed, modified, same = dict_compare(d1, d2)
    print('JSON文件比较结果如下:\n')
    print('增加项:%s\n' % added)
    print('删除项:%s\n' % removed)
    print('修改项:%s\n' % modified)
    print('相同项:%s\n' % same)
    

比较方法2

import json
import deepdiff  # pip install deepdiff

"""
This snippet is used to compare two json files, and find out the differences.
"""
# read json file, return dict file
def file_reader(file_path):
    with open(file_path, 'rb') as json_file:
        file_contents = json.load(json_file)
        return file_contents


if __name__ == "__main__":
    f1_path = './file1.json'
    f2_path = './file2.json'
    d1 = file_reader(f1_path)
    d2 = file_reader(f2_path)
    diff = deepdiff.DeepDiff(d1, d2)
    print('JSON文件比较结果如下:\n')
    print('增加项:%s\n' % diff['dictionary_item_added'])
    print('删除项:%s\n' % diff['dictionary_item_removed'])
    print('修改项:%s\n' % diff['values_changed'])

测试文件

file1.json

{
    "a":{
        "a1": "123",
        "a2": "456"
    },
    "b":{
        "b1": "135",
        "b2": "246"
    },
    "d":{
        "b1": "135",
        "b2": "246"
    }
}

file2.json

{
    "a":{
        "a1": "123",
        "a2": "456"
    },
    "c":{
        "b1": "135",
        "b2": "246"
    },
    "b":{
        "b1": "1357",
        "b2": "246"
    }
}

你可能感兴趣的:(python,python,json,开发语言)