thearnabsarkar commited on
Commit
313f40c
·
verified ·
1 Parent(s): f340460

Upload json_semval/rules_engine.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. json_semval/rules_engine.py +41 -0
json_semval/rules_engine.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict, List, Tuple
4
+
5
+ from jsonschema import Draft202012Validator, FormatChecker
6
+ from jsonschema.exceptions import ValidationError
7
+
8
+ from .jsonpath_utils import path_to_jsonpath
9
+
10
+
11
+ def _to_path_tokens(error: ValidationError) -> List[str]:
12
+ tokens: List[str] = []
13
+ # instance path → tokens
14
+ for p in error.path:
15
+ if isinstance(p, int):
16
+ tokens.append(f"[{p}]")
17
+ else:
18
+ tokens.append(f".{p}")
19
+ return tokens
20
+
21
+
22
+ def _error_to_dict(error: ValidationError) -> Dict[str, Any]:
23
+ tokens = _to_path_tokens(error)
24
+ return {
25
+ "message": error.message,
26
+ "validator": error.validator,
27
+ "validator_value": error.validator_value,
28
+ "jsonpath": path_to_jsonpath(tokens),
29
+ "path_tokens": tokens,
30
+ "schema_path": list(error.schema_path),
31
+ }
32
+
33
+
34
+ def validate_with_jsonschema(
35
+ schema: Dict[str, Any], payload: Any
36
+ ) -> Tuple[bool, List[dict]]:
37
+ validator = Draft202012Validator(schema, format_checker=FormatChecker())
38
+ errors = sorted(validator.iter_errors(payload), key=lambda e: list(e.path))
39
+ if not errors:
40
+ return True, []
41
+ return False, [_error_to_dict(e) for e in errors]