1 # ============LICENSE_START===============================================
2 # Copyright (C) 2020 Nordix Foundation. All rights reserved.
3 # ========================================================================
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 # ============LICENSE_END=================================================
22 # Deep compare of two json obects
23 # If a parameter value in the target json is set to '????' then the result json value is not checked for the that parameter
24 # Any included json array will be sorted before comparison
25 # An optional array key can be given to sort array of objects containing that key
27 def comparejson(jsonTarget,jsonResult,arrayKey):
29 if isinstance(jsonTarget, dict):
30 if (len(jsonTarget) != len(jsonResult)):
32 for key in jsonTarget.keys():
33 if (jsonResult.get(key) is None):
35 if (comparejson(jsonTarget.get(key), jsonResult.get(key), arrayKey) != 0):
37 elif isinstance(jsonTarget, list):
38 if (len(jsonTarget) != len(jsonResult)):
40 if (arrayKey is None):
44 jsonTarget.sort(key=lambda k: k[arrayKey])
45 jsonResult.sort(key=lambda k: k[arrayKey])
47 for i in range(len(jsonTarget)):
48 if (comparejson(jsonTarget[i], jsonResult[i], arrayKey) != 0):
51 if (jsonTarget != "????") and (jsonTarget != jsonResult):
56 jsonTarget = json.loads(sys.argv[1])
57 jsonResult = json.loads(sys.argv[2])
59 if (len(sys.argv) > 3):
60 arrayKey = sys.argv[3]
61 print(comparejson(jsonTarget,jsonResult,arrayKey))
63 except Exception as e: