Comparing JSON Differences in Python Using json_tools and a Custom Recursive Method

The article explains why automated JSON comparison is needed in testing, introduces the json_tools library and a custom recursive approach for detecting differences, shows example outputs, explains the change descriptors, and compares the pros and cons of each method.

360 Quality & Efficiency
360 Quality & Efficiency
360 Quality & Efficiency
Comparing JSON Differences in Python Using json_tools and a Custom Recursive Method

During testing, manually comparing two JSON strings is time‑consuming, so an automated way to detect differences is essential.

The first approach leverages the third‑party Python library json_tools. After installing it with pip install json_tools, you can call its comparison function, which produces a list of change dictionaries such as

[{'replace': '/right', 'value': 'R', 'prev': 'r'}, {'remove': '/box', 'prev': 'b'}, {'add': '/boxs', 'value': 'box'}]

.

The output uses keys like replace (indicating a modified value), add (a newly added key), and remove (a deleted key); each entry also contains the new value ( value) and the previous value ( prev) when applicable.

The second approach is a custom recursive function written by the author, capable of handling deeply nested JSON structures. Its sample output looks like

[{'replace': '/left', 'value': 5, 'prev': 6}, {'add': '/right/ads/des', 'value': '新增键'}, {'remove': '/box/3', 'prev': {'id': 4, 'title': '标题4'}, 'details': 'array-item'}]

, where paths such as /right/ads/des represent nested keys.

Both methods have trade‑offs: using json_tools is straightforward but yields a fixed output format, while the recursive solution offers flexible, customizable reporting at the cost of additional implementation effort.

Overall, the article provides practical guidance for Python developers who need to compare JSON data efficiently in automated tests.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythontestingJSONrecursionJSON Diffjson_tools
360 Quality & Efficiency
Written by

360 Quality & Efficiency

360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.