Поиск разницы между двумя json файлами python

How to compare and find difference between two Json object in python

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

  1. Comparing two json object, return ‘True’ if both json are same otherwise ‘False’
  2. If two json are not equal then find the exact difference.

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.

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, we can use one of the python library called ‘deepdiff’ which will do all the work. To get the difference between jsons, we need to find:

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:

c. Value of key ‘b’ has changed.

DeepDiff function of deepdiff module returns all the changes, lets find all differences using deepdiff:

Output: result is a dictionary which contains all differences.

  1. We have seen easiest way to compare and find the differences in json objects.
  2. ‘==’ is used for comparing json.
  3. DeepDiff function of deepdiff library can be leveraged to find differences.

Источник

Python нужна помощь

Структура data_xxx иерархическая, со многими уровнями вложенности. В то же время если посмотреть, что выдаёт data_xxx:

for data in data_old: print(data)
company_id 
resource
resource_id
status
data
if key in data_old and key in data_new and data_oldПоиск разницы между двумя json файлами python != data_newПоиск разницы между двумя json файлами python:

проверяет различие только на верхнем уровне, не заглядывая внутрь контейнера, поэтому код и не находит различий (key in data_old всегда False).

Поставив диагноз, приступим к лечению. Нам надо не просто пройтись по всем ключам контейнера, но и заглянуть внутрь каждого значения, на случай, если значение само является контейнером.

Читайте также:  Java illegal escape character ошибка

Из-за обработки всякий ситуаций код получился немного громоздким.

def get_difference(container1, container2, diff_list): 

def get_deep_difference(container1, container2, deepcheck):
nonlocal changes, diff_list
diff = False
try:
# Основной цикл по словарю
for key in container1.keys():
check = deepcheck or diff_list and key in diff_list
try:
if get_deep_difference(container1Поиск разницы между двумя json файлами python, container2Поиск разницы между двумя json файлами python, check):
if diff_list and key in diff_list: changesПоиск разницы между двумя json файлами python = container2Поиск разницы между двумя json файлами python
if deepcheck: return True
diff = True
except KeyError: # В container2 отсутствует key
if diff_list and key in diff_list: changesПоиск разницы между двумя json файлами python = None
if deepcheck: return True
diff = True

except AttributeError: # container1 не словарь

if isinstance(container1, str): # строка особый тип, обрабатывается особо
return container1 != container2

try:
# Обработка других типов контейнеров (список, кортеж, множество)
for index, elem in enumerate(container1):
try:
if get_deep_difference(container1[index], container2[index], deepcheck):
if deepcheck: return True
diff = True
except IndexError: return True

except TypeError: return container1 != container2

return diff
# End of get_deep_difference

changes = dict()
get_deep_difference(container1, container2, False)
return changes
# End of get_difference
result = get_difference(data_old, data_new, diff_list) 
print(result)
], 'datetime': '2022-01-25T13:00:00+03:00'>

# Заданный список параметров для отслеживания
diff_list = [«services», «staff», «datetime»]

# Открытие и чтение первого JSON-файла
with open(‘file1.json’, ‘r’) as f1:
data1 = json.load(f1)

# Открытие и чтение второго JSON-файла
with open(‘file2.json’, ‘r’) as f2:
data2 = json.load(f2)

# Поиск различий в значениях заданных ключей в двух JSON-файлах
for param in diff_list:
if data1[param] != data2[param]:
print(f»Различие в значении ключа :»)
print(f»Файл 1: «)
print(f»Файл 2: «)

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Diff JSON and JSON-like structures in Python

License

xlwings/jsondiff

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

…files packaging: revert to requirements files

Git stats

Files

Failed to load latest commit information.

README.rst

Diff JSON and JSON-like structures in Python.

>>> import jsondiff as jd >>> from jsondiff import diff >>> diff('a': 1, 'b': 2>, 'b': 3, 'c': 4>) 'c': 4, 'b': 3, delete: ['a']> >>> diff(['a', 'b', 'c'], ['a', 'b', 'c', 'd']) insert: [(3, 'd')]> >>> diff(['a', 'b', 'c'], ['a', 'c']) delete: [1]> # Typical diff looks like what you'd expect. >>> diff('a': [0, 'b': 4>, 1]>, 'a': [0, 'b': 5>, 1]>) 'a': 1: 'b': 5>>> # . but similarity is taken into account >>> diff('a': [0, 'b': 4>, 1]>, 'a': [0, 'c': 5>, 1]>) 'a': insert: [(1, 'c': 5>)], delete: [1]>> # Support for various diff syntaxes >>> diff('a': 1, 'b': 2>, 'b': 3, 'c': 4>, syntax='explicit') insert: 'c': 4>, update: 'b': 3>, delete: ['a']> >>> diff('a': 1, 'b': 2>, 'b': 3, 'c': 4>, syntax='symmetric') insert: 'c': 4>, 'b': [2, 3], delete: 'a': 1>> >>> diff('list': [1, 2, 3], "poplist": [1, 2, 3]>, 'list': [1, 3]>, syntax="rightonly") "list": [1, 3], delete: ["poplist"]> # Special handling of sets >>> diff('a', 'b', 'c'>, 'a', 'c', 'd'>) discard: set(['b']), add: set(['d'])> # Load and dump JSON >>> print diff('["a", "b", "c"]', '["a", "c", "d"]', load=True, dump=True) "$delete": [1], "$insert": [[2, "d"]]> # NOTE: Default keys in the result are objects, not strings! >>> d = diff('a': 1, 'delete': 2>, 'b': 3, 'delete': 4>) >>> d 'delete': 4, 'b': 3, delete: ['a']> >>> d[jd.delete] ['a'] >>> d['delete'] 4 # Alternatively, you can use marshal=True to get back strings with a leading $ >>> diff('a': 1, 'delete': 2>, 'b': 3, 'delete': 4>, marshal=True) 'delete': 4, 'b': 3, '$delete': ['a']>
jdiff [-h] [-p] [-s ] [-i INDENT] [-f ] first second
-i INDENT , —indent INDENT
Number of spaces to indent. None is compact, no indentation. (default: None)
Читайте также:  Круглые изображения

-f , —format Specify file format for input and dump (default: json)

$ jdiff a.json b.json -i 2 $ jdiff a.json b.json -i 2 -s symmetric $ jdiff a.yaml b.yaml -f yaml -s symmetric

Install development dependencies and test locally with

pip install -r requirements-dev.txt # . do your work . add tests . pytest

To install from source run

This will install the library and cli for jsondiff as well as its runtime dependencies.

About

Diff JSON and JSON-like structures in Python

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

The Python JSON Comparison package

License

rugleb/JsonCompare

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Читайте также:  Scanner java методы nextline

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

The JSON Comparison package

This package is designed to compare two objects with a JSON-like structure and data types.

pip install -U pip jsoncomparison 

First you need to define two variables: expected & actual . Think of them as the same variables that you use in tests.

Expected — the original data object that you want to see. Actual — the given data object.

Then we will transfer these objects to check and identify the difference between them:

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

The check method returns a dictionary of differences between expected and actual objects:

< "project": < "version": < "_message": "Types not equal. Expected: , received: ", "_expected": "str", "_received": "float" >, "license": < "_message": "Values not equal. Expected: , received: ", "_expected": "MIT", "_received": "Apache 2.0" >, "language": < "versions": < "_length": < "_message": "Lengths not equal. Expected , received: ", "_expected": 2, "_received": 1 >, "_content": < "0": < "_message": "Value not found. Expected ", "_expected": 3.5, "_received": null > > > > >, "os": < "_message": "Key does not exists. Expected: ", "_expected": "os", "_received": null > >

The default configuration can be overridden by passing the config dictionary to the Compare class constructor:

from jsoncomparison import Compare config = < "output": < "console": False, "file": < "allow_nan": True, "ensure_ascii": True, "indent": 4, "name": None, "skipkeys": True, >, >, "types": < "float": < "allow_round": 2, >, "list": < "check_length": True, > > > cmp = Compare(config)

By default, the configuration does not allow printing the comparison result to the console, but at the same time writes the results to a file.

These settings can be changed in your class config:

config = < "output": < "console": True, "file": <> > >

What if you do not want to compare some values and keys of objects from your JSON?
In this case, you can define exception rules and pass them to the class constructor.

Let’s go back to the example above:

from jsoncomparison import Compare, NO_DIFF expected = < # . > actual = < # . > rules = < "project": < "version": "*", "license": "*", "language": < "versions": < "_values": [ 3.5 ] > > >, "os": "*", > diff = Compare(rules=rules).check(expected, actual) assert diff == NO_DIFF

Now that we have added exceptions to the missing values, the comparison test has been successfully passed!

You can see a more complex comparison example that I used to test the correct operation of an application: link.

Источник

Оцените статью