If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a and b:

import json

a = json.loads("""
{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}
""")

b = json.loads("""
{
    "success": false,
    "errors": [
        {"error": "required", "field": "name"},
        {"error": "invalid", "field": "email"}
    ]
}
""")
>>> sorted(a.items()) == sorted(b.items())
False

... but that doesn't work, because in each case, the "errors" item of the top-level dict is a list with the same elements in a different order, and sorted() doesn't try to sort anything except the "top" level of an iterable.

To fix that, we can define an ordered function which will recursively sort any lists it finds (and convert dictionaries to lists of (key, value) pairs so that they're orderable):

def ordered(obj):
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    else:
        return obj

If we apply this function to a and b, the results compare equal:

>>> ordered(a) == ordered(b)
True
Answer from Zero Piraeus on Stack Overflow
Top answer
1 of 12
224

If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a and b:

import json

a = json.loads("""
{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}
""")

b = json.loads("""
{
    "success": false,
    "errors": [
        {"error": "required", "field": "name"},
        {"error": "invalid", "field": "email"}
    ]
}
""")
>>> sorted(a.items()) == sorted(b.items())
False

... but that doesn't work, because in each case, the "errors" item of the top-level dict is a list with the same elements in a different order, and sorted() doesn't try to sort anything except the "top" level of an iterable.

To fix that, we can define an ordered function which will recursively sort any lists it finds (and convert dictionaries to lists of (key, value) pairs so that they're orderable):

def ordered(obj):
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    else:
        return obj

If we apply this function to a and b, the results compare equal:

>>> ordered(a) == ordered(b)
True
2 of 12
94

Another way could be to use json.dumps(X, sort_keys=True) option:

import json
a, b = json.dumps(a, sort_keys=True), json.dumps(b, sort_keys=True)
a == b # a normal string comparison

This works for nested dictionaries and lists.

🌐
PyPI
pypi.org › project › json-files-compare
json-files-compare · PyPI
Json-compare is a simple package that allows you to easily and fastly compare two .json files. Support key and multi-key comparison.
      » pip install json-files-compare
    
Published   Feb 05, 2023
Version   1.0.1
🌐
Reddit
reddit.com › r/learnpython › comparing two json files for differences
r/learnpython on Reddit: Comparing Two JSON Files For Differences
August 29, 2022 -

I need to compare two JSON files that contain a list of dictionaries whose basic format is:

[{"protocol": "S", "type": "", "network": "0.0.0.0", "mask": "0", "distance": "254", "metric": "0", "nexthop_ip": "192.168.122.1", "nexthop_if": "", "uptime": ""}, {"protocol": "O", "type": "", "network": "10.129.30.0", "mask": "24", "distance": "110", "metric": "2", "nexthop_ip": "172.20.10.1", "nexthop_if": "GigabitEthernet0/1", "uptime": "08:58:25"}]

Though there are many, many more dictionary items in the list than that shown above. I am not quite sure how best to go about comparing the files to spot differences and return or save those difference to another file, preferably in JSON format, though a CSV would be fine too.

The one gotcha that there may be is I need to exclude, at a minimum, the uptime value as it is constantly changing so it will of course trigger anything looking for changes. Can anyone help get me started please?

🌐
PyPI
pypi.org › project › json-diff
json-diff · PyPI
Generates diff between two JSON files
      » pip install json-diff
    
Published   Aug 25, 2019
Version   1.5.0
🌐
PyPI
pypi.org › project › jsoncomparison
jsoncomparison · PyPI
from jsoncomparison import Compare, NO_DIFF expected = { "project": { "name": "jsoncomparison", "version": "0.1", "license": "MIT", "language": { "name": "python", "versions": [ 3.5, 3.6 ] } }, "os": "linux" } actual = { "project": { "name": "jsoncomparison", "version": 0.1, "license": "Apache 2.0", "language": { "name": "python", "versions": [ 3.6 ] } } } diff = Compare().check(expected, actual) assert diff != NO_DIFF
      » pip install jsoncomparison
    
Published   May 17, 2021
Version   1.1.0
🌐
GitHub
github.com › monsur › jsoncompare
GitHub - monsur/jsoncompare: A simple utility to compare two JSON objects.
jsoncompare is a simple Python utility for comparing two JSON objects USAGE python jsoncompare.py <item1> <item2> Where item1 and item2 are either a file or a url containing a JSON object.
Starred by 22 users
Forked by 27 users
Languages   Python
🌐
GitHub
github.com › rugleb › JsonCompare
GitHub - rugleb/JsonCompare: The Python JSON Comparison package · GitHub
from jsoncomparison import Compare, NO_DIFF expected = { "project": { "name": "jsoncomparison", "version": "0.1", "license": "MIT", "language": { "name": "python", "versions": [ 3.5, 3.6 ] } }, "os": "linux" } actual = { "project": { "name": "jsoncomparison", "version": 0.1, "license": "Apache 2.0", "language": { "name": "python", "versions": [ 3.6 ] } } } diff = Compare().check(expected, actual) assert diff != NO_DIFF
Author   rugleb
🌐
Quora
quora.com › How-do-I-compare-two-JSON-files-in-Python
How to compare two JSON files in Python - Quora
Answer (1 of 5): In Python, the [code ]==[/code] operator is recursive. So if you read in two JSON files, you can compare them like this: [code]doc1 == doc2 [/code]In python, key ordering is preserved, so these two will be printed differently: [code]d1 = {'a': 3, 'b': 4} d2 = {'b': 4, 'a': 3} [...
Find elsewhere
🌐
Medium
medium.com › @abedmaatalla › compare-two-json-objects-python-c2f763c943b0
Compare two JSON objects (Python) | by Abed MAATALLA | Medium
August 4, 2022 - Programmatically, one can write ... writing code and all, This is where deepdiff comes in handy. Deepdiff is a powerful python library to compare 2 dictionaries....
🌐
GitHub
gist.github.com › magnetikonline › 845400198a8e4e4648746a675e955af3
Python - comparing JSON data structures. · GitHub
Python - comparing JSON data structures. ... A function compare_json_data(source_data_a,source_data_b), accepting structures populated with data loaded from json.load() and comparing for equality.
🌐
Reddit
reddit.com › r/learnpython › best way to diff two json files and write differences data to third file?
r/learnpython on Reddit: Best way to diff two JSON files and write differences data to third file?
August 20, 2017 -

Hi all,

I'm trying to write my first python script and I can't work out the best way to diff two JSON files and write the difference to a third.

I've managed to get the script to find differences, but only in entire lines. I want it to either treat it as a JSON, or compare any and all changes, regardless of the line.

Here it is:

a = open('markets.json', 'r').read().split('\n')
b = open('updatemarkets.json', 'r').read().split('\n')
c = open('newpairs.json', 'w')
c.write('\n'.join([comm for comm in b if not (comm in a)]))
c.close()

Obviously the above just duplicates the entire file if any changes are found (as the data is treated as one line).

edit: formatting

edit: this is the data for reference: https://bittrex.com/api/v1.1/public/getmarkets

edit: Difflib doesn't allow you to save the output as it's original format, or create a "patch" like file (in the style of bash's diff/patch). Still looking for a solution!

edit: Maybe a better question is, is it possible to separate JSON objects with a new line at the time of import (json.dump)?

edit: Found how to import the data with a new line using json.dump(data, f, indent=4), but still can't find a way to output the difference between the files.

🌐
TutorialsPoint
tutorialspoint.com › how-to-compare-json-objects-regardless-of-order-in-python
How to Compare JSON Objects Regardless of Order in Python?
In this article, we will explore three different methods for comparing JSON objects in Python regardless of their order. We will discuss techniques for converting JSON objects to dictionaries, sorting JSON objects, and utilizing the jsondiff third?party library to compare JSON objects.
🌐
The Coding Forums
thecodingforums.com › archive › archive › python
how to compare two json file line by line using python? | Python | Coding Forums
May 28, 2013 - The right way is to decode the JSON data, and then compare whether it gives you the result you expect: a = json.load("file-a") b = json.load("file-b") if a == b: print("file-a and file-b contain the same JSON data") If what you care about is ...
🌐
Deviloper's Blog
deviloper.in › advanced-json-diff-checker-in-python-an-in-depth-guide
Advanced JSON Diff Checker in Python: An In-Depth Guide
September 9, 2024 - Feel free to modify json_obj1 and json_obj2 to create your own test scenarios. This way, you can see how the JSON diff checker handles various types of changes and updates. ... Congratulations!
🌐
Python Forum
python-forum.io › thread-28566.html
How to compare two json and write to third json differences with pandas and numpy
Hi I am trying to compare two json and then write another json with columns names and with differences as yes or no. I am using pandas and numpy Input files: And these input files are dynamic, for example this below example file has only two keys,...
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-compare-json-objects-regardless-of-order-in-python
How to compare JSON objects regardless of order in Python? - GeeksforGeeks
January 24, 2021 - For example, if you're working with APIs, you might return a JSON response using frameworks like Flask. Let's explore sever ... In Python, both is and == are used for comparison, but they serve different purposes:== (Equality Operator) → Compares values of two objects.is (Identity Operator) → Compares memory location of two objects.Pythona = [1,2,3] b = [1,2,3] print(a == b) print(a is b) OutputTrue False Explanation: a and
🌐
GitHub
github.com › cpatrickalves › json-diff
GitHub - cpatrickalves/json-diff: A Python script that compares two JSON files and shows their differences.
A Python script that compares two JSON files and shows their differences. - cpatrickalves/json-diff
Author   cpatrickalves
🌐
JSON Diff
jsondiff.com
JSON Diff - The semantic JSON compare tool
Validate, format, and compare two JSON documents. See the differences between the objects instead of just the new lines and mixed up properties.
🌐
YouTube
youtube.com › watch
Compare Two JSON Files in Python | 5 different ways to compare two json in python - YouTube
Hello learner,In this video, you will learn how to compare and check if two json files are identical. And if they are different, what is the actual differenc...
Published   November 26, 2024