| 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) |
|
|