Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

json diff python

# Assumption - json files are of same format, with same keys

# A function to remove duplicate values
def unique(lst):
    unique_lst = []

    # Iterate over the original list and for each element
    # add it to unique_lst, if its not already there.
    for elem in lst:
        if elem not in unique_lst:
            unique_lst.append(elem)
    return unique_lst


# Using dictionary
def compare_json(json_file_1, json_file_2):
    with open(json_file_1, 'r') as f1, open(json_file_2, 'r') as f2:
        data1 = json.load(f1)
        data2 = json.load(f2)
        key_list = set(data1.keys()).union(set(data2.keys()))
        difference = {key: list(set(data1.get(key, [])).difference(set(data2.get(key, []))))
                      for key in key_list}
        return difference


# Using list
def compare_json_2(json_file_1, json_file_2):
    with open(json_file_1, 'r') as f1, open(json_file_2, 'r') as f2:
        data1 = json.load(f1)
        data2 = json.load(f2)
        #Assuming both json files have same format
        key_list = data1.keys()
        difference = {}
        for key in key_list:
            difference[key] = list(set(data1[key]).difference(set(data2[key])))
            difference[key] = unique(difference[key])
        return difference


print(compare_json('json_1.json', 'json_2.json'))
print(compare_json_2('json_1.json', 'json_2.json'))
 
PREVIOUS NEXT
Tagged: #json #diff #python
ADD COMMENT
Topic
Name
7+2 =