Compare two JSON objects (Python)
![]()
In this short article, we will see quick and easiest way to perform comparison on Json object in python:
- Comparing two json object, return ‘True’ if both json are same otherwise
- ‘False’
- Edge case of comparing json objects using “==”
- If two json are not equal then find the exact difference.
1. Comparing Json:
Comparing json is quite simple, we can use ‘==’ operator,
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.
2. Edge case of comparing Json object using “==”:
Comparing two dictionaries has been solved in the first part of this articles. Now let’s image we have the following dicts to compare :
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)
But order is important in list; sorting will solve the problem for the lists.
Above example will work for the JSON in the question.
3. Difference in Jsons:
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.
DeepDiff function of deepdiff module returns all the changes, let's find all differences using deepdiff:
how to compare 2 json in python [closed]
How to compare 2 json objects in python below are the sample json.
2 Answers 2
It seems that the usual comparison working properly
these are not valid JSON / Python objects, because array / list literals are inside [] instead of <> :
UPDATE: to compare list of dictionaries (serialized JSON array of objects), while ignoring the order of list items, the lists need to be sorted or converted to sets:
Python-сообщество
Давай забудем про то что тут написанно
Итак у нас есть два словаря! Тебе их нужно сравнить! Сравнить по какому параметру? Что должно быть для них результатом?
Влодение рускай арфаграфией — это как владение кунг-фу: настаящие мастира не преминяют ево бес ниабхадимости
#3 Окт. 30, 2022 17:49:59
Сравнить два json-объекта
Понял, неудачно описал проблему)
Есть два словаря, оба получаю из json-файлов, пример словарей в первом сообщении. Нужно сравнить их по двум условиям:
1. Нужно сравнить на предмет совпадения все значения “а” из словаря d1 со всеми значениями “с” словаря d2.
Например, в словаре d2 есть запись <“c”: “Ivan”, “d”: 5, “e”: 15>.сравнив ее с данными словаря d1, мы видим, что будут подходить два варианта <“a”: “Ivan”, “b”: 10>,<“a”: “Ivan”, “b”: 20>.
2.Если “а” и “с” совпадают, то нужно сравнить значения “b” из словаря d1 с значениями “d” и “e” из словаря d2 по формуле: d < b < e
Например: в пункте 1 в словаре d2 значения ключей d и e равны 5 и 15 соответственно. В словаре d1 ключи b равны 10 в первом варианте и 20 во втором. Сравнив их по формуле d < b < e (5 < 10 < 15, 5 < 20 < 15), получаем, что подходит только вариант со значением 10.
И так нужно сравнить весь словарь d1 со всем словарём d2.
Итого, нужно вывести в реультат все значения из словаря d1, которые подходят под эти 2 условия, а именно: Ivan 10, Egor 5, Petya 17, Vasya 12.
Надеюсь, понятно объяснил. Задавайте вопросы, если что-то еще нужно уточнить.
Отредактировано Injector (Окт. 30, 2022 17:53:09)
#4 Окт. 30, 2022 21:36:22
Сравнить два json-объекта
Общий принцип такой: надо постоянно отсекать понемногу от общей массы и потом работать с тем, что осталось.
Общий принцип такой: надо итеративным образом отсекать понемногу от общей массы, оставляя максимум от всего остального, и потом работать с тем, что осталось, повторяя всю эту процедуру снова для оставшейся общей массы. Это процесс декомпозиции.
Это как есть торт: надо отрезать по кусочку, съедать кусочек, потом снова отрезать кусочек и съедать кусочек, и так далее, так ты съешь весь торт; если же ты его будешь сразу заталкивать весь в рот и пытаться проглатывать его весь, то можно и вовсе подавиться этим всем и задохнуться в итоге.
Тут сначала структура словаря отделена от списков, с которыми надо работать. Чтобы с этими списками работать, структура общего словаря не нужна, поэтому отрезаем её и выкидываем. Дальше работаем только со списками словарей.
Затем нам надо выбрать нужные словари из списков, не делая ничего с ними, поэтому сами списки, которые нам не нужны со всеми ненужными словарями в них, мы отрезаем и выкидываем.
И потом, получив нужные словари, мы уже работаем только с ними и начинаем их выводить как-то или выбирать что-то из них.
С каждым шагом остаётся все меньше данных и они становятся всё точнее и определённее.
json-compare
Json-compare is a simple package that allows you to easily and fastly compare two .json files. Support key and multi-key comparison. You can also ignore certain fields’ values or perform comparison insensitive to data types.
Usage
Compare files just as they are:
Set key property to perform more accurate comparisons of objects in arrays:
In this case, saved diff log would look like that:
You can go further and add non-important fields to ignore parameter:
And here the result:
If you want to compare ignoring type-differences between similar values like «1.4» vs 1.4 or «[\»New Age №1\»]» vs [«New Age №1»] — just add ignore_types=True param to JSONComparator: