jsoneditor.py 2.77 KB
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):
        # End of the json path

        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.")
            else:
                # If dictionary in both cases, copy from content to pointer
                if way in pointer and type(pointer[way]) is dict and type(content_data) is dict:
                    for key in content_data:
                        pointer[way][key] = content_data[key]
                else:
                    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")