Commit f0ca26aaf4157c681c3bc3ac351edfbb3b1913c5

Authored by quillotm
1 parent b479f46e1e
Exists in master

This script permits, for now, to write json using script pipelines.

Showing 1 changed file with 80 additions and 0 deletions Side-by-side Diff

  1 +import json
  2 +import argparse
  3 +from utils import SubCommandRunner
  4 +import json
  5 +from os import path
  6 +import sys
  7 +
  8 +def write_run(file, jsonpath, content, force):
  9 +
  10 + if content is None:
  11 + content = ""
  12 + for line in sys.stdin:
  13 + content += line
  14 +
  15 + # Data variables
  16 + content_data = json.loads(content)
  17 + data = {}
  18 +
  19 + # Load file if necessary
  20 + if path.isfile(file):
  21 + with open(file, "r") as f:
  22 + data = json.load(f)
  23 +
  24 + # Walk through the json path
  25 + pointer = data
  26 + for i, way in enumerate(jsonpath):
  27 + if i == len(jsonpath) - 1:
  28 + if not force and way in pointer:
  29 + raise Exception(f"In your json file, {way} already exists in the path {jsonpath}. Add --force option.")
  30 + pointer[way] = content_data
  31 + else:
  32 + if way not in pointer:
  33 + pointer[way] = {}
  34 + pointer = pointer[way]
  35 +
  36 + # Write the file
  37 + with open(file, "w") as f:
  38 + json.dump(data, f)
  39 +
  40 +
  41 +if __name__ == "__main__":
  42 + # Main parser
  43 + parser = argparse.ArgumentParser(description="Edite a json file using this command")
  44 + subparsers = parser.add_subparsers(title="action")
  45 +
  46 + # kmeans
  47 + parser_write = subparsers.add_parser(
  48 + "write",
  49 + help="""Allow you to add content to a json file.
  50 +If the json file does not exists, it will create the json file with a dictionary as root.
  51 +
  52 +Example of command:
  53 +python -m volia.jsoneditor write file.json --jsonpath 6 "entropy" --content "[6, 6, 8] --force
  54 +
  55 +You can also use pipeline functionality to use the output of a command as the added content in the json.
  56 +
  57 +Example of pipeline command:
  58 +echo "2.06" | python -m volia.jsoneditor write file.json --jsonpath 6 "entropy" --force
  59 +
  60 +""")
  61 +
  62 + parser_write.add_argument("file", type=str, help="json file")
  63 + parser_write.add_argument("--jsonpath",
  64 + required=True,
  65 + nargs="+",
  66 + help="json path, example: a b => root[a]['b'] if a int and b str")
  67 + parser_write.add_argument("--content", default=None, type=str, help="json content to add")
  68 + parser_write.add_argument("--force", action="store_true", help="force to rewrite if the key already exists")
  69 + parser_write.set_defaults(which="write")
  70 +
  71 + # Parse
  72 + args = parser.parse_args()
  73 +
  74 + # Run commands
  75 + runner = SubCommandRunner({
  76 + "write": write_run,
  77 + })
  78 +
  79 + runner.run(args.which, args.__dict__, remove="which")