Commit 09f3471d674f668550f9ffd03247414e7a5f0154

Authored by quillotm
1 parent 3e2abe83e3
Exists in master

Now, you can add elements to and existing dictionary by giving an input dictionary (content).

Showing 1 changed file with 10 additions and 1 deletions Inline Diff

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