Instead of converting the JSON response into Object, I use json.loads() to convert it into a Dictionary, and compare them.

def test_login(self, client):
        res = return client.post('/login',
            data=json.dumps(dict(staff_name='no_such_user', staff_password='password')),
            content_type='application/json',
            follow_redirects=True)
        assert res.status_code == 422
        invalid_password_json = dict(message="Staff name and password pair not match",
                                    errors=dict(
                                        resource="Login",
                                        code="invalid",
                                        field="staff_authentication",
                                        stack_trace=None,),
                                    )
        assert json.loads(res.data) == invalid_password_json

This way, I do not have to worry about whitespace differences in the JSON response, as well as ordering of the JSON structure. Simply let Python's Dictionary comparison function check for equality.

Answer from Hanxue on Stack Overflow
🌐
GitHub
gist.github.com › magnetikonline › 845400198a8e4e4648746a675e955af3
comparing JSON data structures. - Python - Gist - GitHub
JSON files a.json and b.json are loaded via load_json() function and structures passed into compare_json_data() for comparison.
🌐
Blogger
hanxue-it.blogspot.com › 2017 › 10 › pytest-testing-and-comparing-json-response-using-pytest-flask.html
Hanxue and IT: Pytest: Testing and Comparing JSON Response Using Pytest-Flask
October 18, 2017 - Let's say we have a Flask API endpoint that returns this JSON { "message": "Staff name and password pair not match", "errors": { ...
🌐
Medium
medium.com › @abedmaatalla › compare-two-json-objects-python-c2f763c943b0
Compare two JSON objects (Python) | by Abed MAATALLA | Medium
August 4, 2022 - If two json are not equal then find the exact difference. Comparing json is quite simple, we can use ‘==’ operator,
Top answer
1 of 1
1

I do believe you could check every keys and values. You should first check the set of keys are equal in both sides, then key by key comparison will make sense.

assert(data_1.keys() == data_2.keys())
err_log = [['Err log:']] 
for k, v in data_1.items():
    try:
        assert(v == data_2[k])
    except:
        err_log.append(['Error catched for key=', k, ', data_1 value=', v, ', data_2 value=', data_2[k]])
[print(str(e)) for e in err_log]

Edit 3: Tested on very big dictionaries.

Best results are obtained with itemgetter of sorted list of keys for very large dictionaries.

Iterating through all keys of dictionaries is the worst. Iterating with ordered list of keys seems to perform slightly better.

Results:

  • n = 100:
    • 4e-3 seconds
    • 3e-3 seconds
    • 1.5e-3 seconds
    • 1.9e-3 seconds
  • n = 1,000,000:
    • 8.9 seconds
    • 9.2 seconds
    • 7.2 seconds
    • 6.9 seconds
  • n = 10,000,000:
    • 143 seconds
    • 130 seconds
    • 115 seconds
    • 99 seconds
from copy import deepcopy
from time import time
from operator import itemgetter

n = 10000000
v = {"stuff": "here", "and": "there"}
data_1 = {str(k): deepcopy(v) for k in range(0, n)}
data_2 = {str(k): deepcopy(v) for k in range(n-1, -1, -1)}

def get_time(f):
    def _(*args, **kwargs):
        t_0 = time()
        for x in range(10):
            f(*args, **kwargs)
        return time() - t_0
    return _

def with_dict_keys(d):
    return d.keys()

def with_sorted_dict_keys(d):
    return sorted(d.keys())

@get_time
def order_n_compare(key_func, d, d_):
    k_d, k_d_ = key_func(d), key_func(d_)
    assert(k_d == k_d_)
    for k in k_d:
        assert(d[k] == d_[k])


@get_time
def itemgetter_compare(key_func, d, d_):
    k_d, k_d_ = key_func(d), key_func(d_)
    assert(k_d == k_d_)
    assert(itemgetter(*k_d)(d) == itemgetter(*k_d)(d_))
Edit 0: added try & except block to print out where assertions are wrong
Edit 1: fixed minor bug
Edit 2: Check computation time: the dictionnary.keys() operation is irrelevant over iterating through all keys in data_1.items() because it grows order n. So it's not really necessary to optimize it.
  • Note: If sorting dict.keys() is order(log(n)) then the operation time of getting dict.keys() seems to be order log(n) too.
🌐
GitHub
github.com › rugleb › JsonCompare
GitHub - rugleb/JsonCompare: The Python JSON Comparison package · GitHub
from jsoncomparison import Compare, NO_DIFF expected = { # ... } actual = { # ...
Starred by 68 users
Forked by 23 users
Languages   Python 95.8% | Makefile 4.2%
🌐
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 › jsoncomparison
jsoncomparison · PyPI
from jsoncomparison import Compare, NO_DIFF expected = { # ... } actual = { # ...
      » pip install jsoncomparison
    
Published   May 17, 2021
Version   1.1.0
Find elsewhere
🌐
PyPI
pypi.org › project › json-diff
json-diff · PyPI
Compares two JSON files (http://json.org) and generates a new JSON file with the result.
      » pip install json-diff
    
Published   Aug 25, 2019
Version   1.5.0
🌐
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 - So, in such cases we can define a custom function ourselves that can recursively sort any list or dictionary (by converting dictionaries into a list of key-value pair) and thus they can be made fit for comparison. Implementation using this alternative is given below. ... import json # JSON string json_1 = '{"Name":"GFG", "Class": "Website", "Domain":"CS/IT", "CEO":"Sandeep Jain","Subjects":["DSA","Python","C++","Java"]}' json_2 = '{"CEO":"Sandeep Jain","Subjects":["C++","Python","DSA","Java"], "Domain":"CS/IT","Name": "GFG","Class": "Website"}' # Convert string into Python dictionary json1_dic
🌐
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} [...
🌐
TutorialsPoint
tutorialspoint.com › how-to-compare-json-objects-regardless-of-order-in-python
How to Compare JSON Objects Regardless of Order in Python?
July 20, 2023 - In the above example, we utilized the json.loads method provided by Python's built?in json module to convert the JSON objects json_obj1 and json_obj2 to dictionaries. subsequently, we compared the two dictionaries using the == operator.
🌐
PyPI
pypi.org › project › pytest-json
pytest-json · PyPI
A formatted example of the jsonapi output can be found in example_jsonapi.json · Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request. Distributed under the terms of the MIT license, “pytest-json” is free and open source software
      » pip install pytest-json
    
Published   Jan 18, 2016
Version   0.4.0
🌐
Damir's Corner
damirscorner.com › blog › posts › 20220520-ComparingJsonStringsInUnitTests.html
Comparing JSON strings in unit tests | Damir's Corner
May 20, 2022 - You can compare them as strings, but for that to work you need to use consistent formatting that ensures the same data is always serialized into identical JSON, for example something like the JSON Canonical Form.
🌐
Edureka Community
edureka.co › home › community › categories › python › how to compare two json objects with the same...
How to compare two JSON objects with the same elements in a different order equal | Edureka Community
August 7, 2020 - How can I test whether two JSON objects are equal in python, disregarding the order of lists? For ... the order of the "errors" lists are different.
🌐
Pytest with Eric
pytest-with-eric.com › pytest-best-practices › pytest-read-json
5 Easy Ways To Read JSON Input Data In Pytest | Pytest with Eric
May 29, 2023 - Here we’ve used the pathlib module to parse the file but you can also use the json module. The benefit here is we decouple the input from the test module, but you’ll run into test errors if the input file is unavailable. Another way (and one I’m a big fan of) is to provide your input data as a Pytest fixture.
🌐
Readthedocs
pytest-benchmark.readthedocs.io › en › latest › comparing.html
Comparing past runs - pytest-benchmark 5.2.3 documentation
You should add --benchmark-autosave ... want to give specific name to the run. After you have saved your first run you can compare against it with --benchmark-compare=0001....
🌐
GitHub
github.com › davidpdrsn › assert-json-diff
GitHub - davidpdrsn/assert-json-diff: Easily compare two JSON values and get great output
This crate includes macros for comparing two serializable values by diffing their JSON representations. It is designed to give much more helpful error messages than the standard assert_eq!.
Starred by 90 users
Forked by 18 users
Languages   Rust 97.4% | Shell 2.6% | Rust 97.4% | Shell 2.6%
🌐
Readthedocs
pytest-benchmark.readthedocs.io › en › latest › usage.html
Usage - pytest-benchmark 5.2.3 documentation
pytest-benchmark compare /foo/bar/0001_abc.json /lorem/ipsum/0001_sir_dolor.json
🌐
GitHub
github.com › numirias › pytest-json-report › compare
Compare · numirias/pytest-json-report
🗒️ A pytest plugin to report test results as JSON. Contribute to numirias/pytest-json-report development by creating an account on GitHub.
Author   numirias