7 EXPR_RE = re.compile('(?P<label>[a-zA-Z0-9_-]+):(?P<address>[^=!]+)(?:(?P<type>[=!])(?P<val>.*))?', re.DOTALL|re.MULTILINE)
11 sys.exit('usage: '+ sys.argv[0] + """ EXPR [EXPR]
13 Takes json data on stdin and evaluates test expressions specified in
14 arguments. Each test is evaluated, and output is printed only if the
15 test fails. If any test fails the return value of execution will be
18 EXPR can be one of following types:
20 Value test: test that object in json data found at address is equal to
25 Existence test: test that dict or list in json data found at address
26 does *not* contain the specified key:
30 Extract: extract object from json data found at address and print
34 Results are printed to stdout prefixed by expression label. In all
35 cases the test will fail if object does not exist in data.
39 0 $ echo '["a", "b", {"c": 1}]' | python3 json_check_nodes.py 'second_d:[1]="d"' 'no_c:[2]!"c"'
40 second_d: value not equal: data[1] = 'b' != 'd'
41 no_c: dict contains key: data[2]["c"] = 1
47 # parse expressions from arguments
49 for expr in sys.argv[1:]:
50 m = re.match(EXPR_RE, expr)
52 sys.exit("Invalid expression: {}".format(expr))
55 data = json.load(sys.stdin)
60 # print(expr.groups(),fail)
62 e = 'data{}'.format(expr.group('address'))
67 print("{}: syntax error on evaluation of object: {}".format(
68 expr.group('label'), e))
72 print("{}: object not found: data{}".format(
73 expr.group('label'), expr.group('address')))
76 if expr.group('type') == '=':
78 obj_val = json.loads(expr.group('val'))
81 print("{}: error evaluating value: {}".format(
82 expr.group('label'), expr.group('address')))
86 print("{}: value not equal: data{} = {} != {}".format(
87 expr.group('label'), expr.group('address'), repr(val), repr(obj_val)))
89 elif expr.group('type') == '!':
90 if not isinstance(val, (dict, list)):
92 print("{}: not a dict or a list: data{}".format(
93 expr.group('label'), expr.group('address')))
96 idx = json.loads(expr.group('val'))
99 print("{}: {} contains key: {}[{}] = {}".format(
100 expr.group('label'), type(val).__name__, e, expr.group('val'), val[idx]))
103 print("{}: syntax error on evaluation of value: {}".format(
104 expr.group('label'), expr.group('val')))
108 elif expr.group('type') is None:
109 print("{}: {}".format(expr.group('label'), val))