Compare two JSON objects (Python) (2024)

In this short article, we will see quick and easiest way to perform comparison on Json object in python:

Compare two JSON objects (Python) (2)
  1. Comparing two json object, return ‘True’ if both json are same otherwise
  2. ‘False’
  3. Edge case of comparing json objects using “==”
  4. If two json are not equal then find the exact difference.

Comparing json is quite simple, we can use ‘==’ operator,

Compare two JSON objects (Python) (3)
Compare two JSON objects (Python) (4)

Note: ‘==’ and ‘is’ operator are not same, ‘==’ operator is use to check equality of values , whereas ‘is’ operator is used to check reference equality, hence one should use ‘==’ operator, ‘is’ operator will not give expected result.

Comparing two dictionaries has been solved in the first part of this articles. Now let’s image we have the following dicts to compare :

Dict 1 :

{
"errors": [
{"error": "invalid", "field": "email"},
{"error": "required", "field": "name"}
],
"success": false
}

Dict 2 :

{
"success": false,
"errors": [
{"error": "required", "field": "name"},
{"error": "invalid", "field": "email"}
]
}
>>> dict1 == dict2
False

let’s decode them and compare. Order does not matter for dictionary as long as the keys, and values matches. (Dictionary has no order in Python)

>>> {'a': 1, 'b': 2} == {'b': 2, 'a': 1}
True

But order is important in list; sorting will solve the problem for the lists.

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

Above example will work for the JSON in the question.

Finding exact difference in two json sounds difficult task, it may become even more difficult, if we try to find differences in nested jsons. Programmatically, one can write a small piece of code which would iterate every keys of json and pick the differences, but this work will become very difficult if we don’t know how nested the json is. But, we don’t really have to worry of writing code and all, This is where deepdiff comes in handy. Deepdiff is a powerful python library to compare 2 dictionaries. What makes it powerful is that, during the comparison, deepdiff does not consider the order in which the elements inside the dictionaries are present.
Let’s see deepdiff in action :

1.Elements newly added.

2. Elements removed.

3. Elements whose values changed.

Consider below example, jsn_1 contains three items with keys ‘a’,’b’,’c’ respectively, in jsn_2 below changes has been done:

a. Element ‘c’ is removed.

b. Element ‘e’ and ‘d’ added.

c. Value of key ‘b’ has changed.

Compare two JSON objects (Python) (5)

DeepDiff function of deepdiff module returns all the changes, let's find all differences using deepdiff:

Compare two JSON objects (Python) (6)
Compare two JSON objects (Python) (7)

Elements Added:

Compare two JSON objects (Python) (8)

Elements Removed:

Compare two JSON objects (Python) (9)

Values changed:

Compare two JSON objects (Python) (10)

Conclusion:

  1. We have seen easiest way to compare and find the differences in json objects.
  2. ‘==’ is used for comparing json.
  3. Dictionary has no order in Python but order is important in list
  4. DeepDiff function of deepdiff library can be leveraged to find differences.
Compare two JSON objects (Python) (2024)
Top Articles
35+ useful document and file comparison tools | The Jotform Blog
10 common credit card mistakes you may be making and how to avoid them
Fat Hog Prices Today
Garrison Blacksmith Bench
O'reilly's Auto Parts Closest To My Location
Www.craigslist Virginia
Angela Babicz Leak
Chatiw.ib
Find All Subdomains
Kris Carolla Obituary
Riegler & Partner Holding GmbH auf LinkedIn: Wie schätzen Sie die Entwicklung der Wohnraumschaffung und Bauwirtschaft…
Red Heeler Dog Breed Info, Pictures, Facts, Puppy Price & FAQs
Weekly Math Review Q4 3
Simple Steamed Purple Sweet Potatoes
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Elbasha Ganash Corporation · 2521 31st Ave, Apt B21, Astoria, NY 11106
Find Such That The Following Matrix Is Singular.
Kayky Fifa 22 Potential
Forest Biome
Clare Briggs Guzman
Holiday Gift Bearer In Egypt
Riversweeps Admin Login
3 2Nd Ave
Dark Entreaty Ffxiv
Unity Webgl Car Tag
Weather October 15
Tamil Movies - Ogomovies
Desales Field Hockey Schedule
Trust/Family Bank Contingency Plan
Issue Monday, September 23, 2024
Ellafeet.official
Craigslist Central Il
Dreamcargiveaways
How to Draw a Bubble Letter M in 5 Easy Steps
Metra Union Pacific West Schedule
The Ride | Rotten Tomatoes
Sinfuldeeds Vietnamese Rmt
How to Destroy Rule 34
Aliciabibs
Unifi Vlan Only Network
2007 Peterbilt 387 Fuse Box Diagram
Mcalister's Deli Warrington Reviews
Lyndie Irons And Pat Tenore
Craigslist Com St Cloud Mn
Value Village Silver Spring Photos
Rocket Bot Royale Unblocked Games 66
Causeway Gomovies
Image Mate Orange County
Helpers Needed At Once Bug Fables
March 2023 Wincalendar
Tamilblasters.wu
4015 Ballinger Rd Martinsville In 46151
Latest Posts
Article information

Author: Rev. Porsche Oberbrunner

Last Updated:

Views: 6270

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Rev. Porsche Oberbrunner

Birthday: 1994-06-25

Address: Suite 153 582 Lubowitz Walks, Port Alfredoborough, IN 72879-2838

Phone: +128413562823324

Job: IT Strategist

Hobby: Video gaming, Basketball, Web surfing, Book restoration, Jogging, Shooting, Fishing

Introduction: My name is Rev. Porsche Oberbrunner, I am a zany, graceful, talented, witty, determined, shiny, enchanting person who loves writing and wants to share my knowledge and understanding with you.