jsoneditor.py
2.77 KB
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
88
89
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")