From f0ca26aaf4157c681c3bc3ac351edfbb3b1913c5 Mon Sep 17 00:00:00 2001 From: quillotm Date: Thu, 12 Aug 2021 11:36:04 +0200 Subject: [PATCH] This script permits, for now, to write json using script pipelines. --- volia/jsoneditor.py | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 volia/jsoneditor.py diff --git a/volia/jsoneditor.py b/volia/jsoneditor.py new file mode 100644 index 0000000..0f44da2 --- /dev/null +++ b/volia/jsoneditor.py @@ -0,0 +1,80 @@ +import json +import argparse +from utils import SubCommandRunner +import json +from os import path +import sys + +def write_run(file, jsonpath, content, force): + + if content is None: + content = "" + for line in sys.stdin: + content += line + + # Data variables + content_data = json.loads(content) + data = {} + + # Load file if necessary + if path.isfile(file): + with open(file, "r") as f: + data = json.load(f) + + # Walk through the json path + pointer = data + for i, way in enumerate(jsonpath): + if i == len(jsonpath) - 1: + if not force and way in pointer: + raise Exception(f"In your json file, {way} already exists in the path {jsonpath}. Add --force option.") + pointer[way] = content_data + else: + if way not in pointer: + pointer[way] = {} + pointer = pointer[way] + + # Write the file + with open(file, "w") as f: + json.dump(data, f) + + +if __name__ == "__main__": + # Main parser + parser = argparse.ArgumentParser(description="Edite a json file using this command") + subparsers = parser.add_subparsers(title="action") + + # kmeans + parser_write = subparsers.add_parser( + "write", + help="""Allow you to add content to a json file. +If the json file does not exists, it will create the json file with a dictionary as root. + +Example of command: +python -m volia.jsoneditor write file.json --jsonpath 6 "entropy" --content "[6, 6, 8] --force + +You can also use pipeline functionality to use the output of a command as the added content in the json. + +Example of pipeline command: +echo "2.06" | python -m volia.jsoneditor write file.json --jsonpath 6 "entropy" --force + +""") + + parser_write.add_argument("file", type=str, help="json file") + parser_write.add_argument("--jsonpath", + required=True, + nargs="+", + help="json path, example: a b => root[a]['b'] if a int and b str") + parser_write.add_argument("--content", default=None, type=str, help="json content to add") + parser_write.add_argument("--force", action="store_true", help="force to rewrite if the key already exists") + parser_write.set_defaults(which="write") + + # Parse + args = parser.parse_args() + + # Run commands + runner = SubCommandRunner({ + "write": write_run, + }) + + runner.run(args.which, args.__dict__, remove="which") + -- 1.8.2.3