python json文件对比方法

#file1.json
{
    'a':{
        'a1':'123'
        'a2':'456'
    }
    'b':{
        'b1':'acs'
        'b2':'abc'
    }
}
#file1.json
{
    'a':{
        'a1':'123'
        'a2':'656'
    }
    'c':{
        'c1':'acs'
        'c2':'abc'
    }
}

#coding:utf-8
import os
import json

def get_MD5(file_path):
    '''利用mac 终端命令计算MD5'''
    files_md5 = os.popen('md5 %s' % file_path).read().strip()
    file_md5 = files_md5.replace('MD5 (%s) = ' % file_path, '')
    return file_md5


#读取json 文件
def load_json(file):
    with open(file) as f:
        load_f = json.load(f)
    return load_f

file1 = load_json('file1.json')
file2 = load_json('file2.json')

if get_MD5(file1) != get_MD5(file2):
    for key in file1.keys():
        if key not in file1.keys():
            print "健不同的:" + key
        else:
            if file2[key] != file1[key]:
                print "健相同,值不同的:" + key 


'''
1.这个对比方法 是以其中一个json 文件为依据 找出另一个json 文件与其不同的地方
2.先对比了2个文件的MD5 确认2个文件是不同的 则开始进行对比内容
3.可用 file.keys() 进行 健 的对比,然后使用file[key] 进行值的对比
'''

猜你喜欢

转载自blog.csdn.net/weixin_42934547/article/details/81806089