File size: 2,373 Bytes
d180a03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a6a1a5
d180a03
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import argparse
from pathlib import Path
import json
import sys

import json5
import jsonpath_ng
from jsonpath_ng.ext import parse


def update(keyword, keyword_val):
    def _update(orig, data, field):
        orig[keyword] = keyword_val
        return orig

    return _update


def main(input_file, schema_dir):
    if input_file == "-":
        input_file = sys.stdin
    else:
        input_file = open(input_file)

    for line in input_file:
        obj = json.loads(line)
        schemas = {}
        if obj["is_neg"]:
            try:
                path = parse(obj["path"])
            except (
                jsonpath_ng.exceptions.JsonPathParserError,
                jsonpath_ng.exceptions.JsonPathLexerError,
            ):
                continue

            schema_path = (
                Path(schema_dir)
                / obj["schema"]
            )
            if obj["schema"] not in schemas:
                try:
                    schemas[obj["schema"]] = json.load(schema_path.open())
                except json.decoder.JSONDecodeError:
                    schemas[obj["schema"]] = None
                    continue
                except FileNotFoundError:
                    schemas[obj["schema"]] = None
                    continue

            schema = schemas[obj["schema"]]

            keyword_path = jsonpath_ng.Child(path, jsonpath_ng.Fields(obj["keyword"]))
            try:
                keyword_vals = keyword_path.find(schema)
            except KeyError:
                continue
            if len(keyword_vals) > 0:
                keyword_val = keyword_vals[0].value

                try:
                    path.update(obj["obj"], update(obj["keyword"], keyword_val))
                except IndexError:
                    continue
            else:
                continue

        json.dump(
            {
                "schema": obj["schema"],
                "keyword": obj["keyword"],
                "obj": json.dumps(obj["obj"]),
                "is_neg": obj["is_neg"],
            },
            sys.stdout,
        )
        sys.stdout.write("\n")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input", type=str, default="-")
    parser.add_argument("-s", "--schema-dir", type=str)
    args = parser.parse_args()

    main(args.input, args.schema_dir)