You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
2.1 KiB
51 lines
2.1 KiB
|
6 days ago
|
import json
|
||
|
|
from numbers import Number
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
|
||
|
|
def _type(v):
|
||
|
|
if v is None: return "null"
|
||
|
|
if isinstance(v, bool): return "bool"
|
||
|
|
if isinstance(v, int): return "int"
|
||
|
|
if isinstance(v, float): return "float"
|
||
|
|
if isinstance(v, str): return "str"
|
||
|
|
if isinstance(v, list): return "list"
|
||
|
|
if isinstance(v, dict): return "dict"
|
||
|
|
return type(v).__name__
|
||
|
|
|
||
|
|
|
||
|
|
def compare(xml_data: dict, json_data: dict, path="$") -> list[dict[Any, Any]] | list:
|
||
|
|
type_xml, type_json = _type(xml_data), _type(json_data)
|
||
|
|
if type_xml != type_json:
|
||
|
|
return [
|
||
|
|
{"path": path, "desc": "diff_type", "xml_type": type_xml, "xml_value": xml_data, "json_type": type_json,
|
||
|
|
"json_value": json_data}]
|
||
|
|
if type_xml == "dict":
|
||
|
|
diff = []
|
||
|
|
for k in xml_data.keys() - json_data.keys():
|
||
|
|
diff.append({"path": f"{path}.{k}", "desc": "only_in_xml", "xml_type": k, "xml_value": xml_data[k]})
|
||
|
|
for k in json_data.keys() - xml_data.keys():
|
||
|
|
diff.append({"path": f"{path}.{k}", "desc": "only_in_json", "json_type": k, "json_value": json_data[k]})
|
||
|
|
for k in xml_data.keys() & json_data.keys():
|
||
|
|
diff.extend(compare(xml_data[k], json_data[k], f"{path}.{k}"))
|
||
|
|
return diff
|
||
|
|
if type_xml == "list":
|
||
|
|
diffs, n = [], min(len(xml_data), len(json_data))
|
||
|
|
for i in range(n):
|
||
|
|
diffs.extend(compare(xml_data[i], json_data[i], f"{path}[{i}]"))
|
||
|
|
for i in range(n, len(xml_data)):
|
||
|
|
diffs.append({"path": f"{path}[{i}]", "desc": "only_in_xml", "xml_type": _type(xml_data[i]),
|
||
|
|
"xml_value": xml_data[i]})
|
||
|
|
for i in range(n, len(json_data)):
|
||
|
|
diffs.append({"path": f"{path}[{i}]", "desc": "only_in_json", "xml_type": _type(json_data[i]),
|
||
|
|
"xml_value": json_data[i]})
|
||
|
|
return diffs
|
||
|
|
elif xml_data == json_data:
|
||
|
|
return []
|
||
|
|
return [{"path": path, "desc": "need_check", "xml_type": _type(xml_data), "xml_value": xml_data,
|
||
|
|
"json_type": _type(json_data), "json_value": json_data}]
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == '__main__':
|
||
|
|
pass
|