-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_cli.py
80 lines (65 loc) · 2.24 KB
/
json_cli.py
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
import json, os
import re, types
class json_cli():
def __init__(self):
self.fields = {}
def handle_pair(self, level, key, value, path=None):
type = self.get_type(value)
if path :
path +="/"+key
else:
path =key
if type == dict:
for item in value:
self.handle_pair(level+1, item, value[item], path)
elif type == list:
for i in value:
self.handle_pair(level+1, "list/" +
str(value.index(i)),i, path)
else:
self.render(level, type, key, value, path)
return
def get_type(self, value):
if isinstance(value, str):
type=str
elif isinstance(value, bool):
type=bool
elif isinstance(value, int):
type=int
elif isinstance(value, float):
type = float
elif isinstance(value, list):
type = list
elif isinstance(value, dict):
type = dict
return type
def render(self, level, type, key, value, path):
print("{}: {}: {}".format(level, path,
#Added encode to supppor web queries as it was erroring out without it
str(value).encode("utf-8")))
return
def load_file(self, data_file):
with open(data_file) as infile:
self.all_data = json.load(infile)
self.handle_pair( 0, "", self.all_data)
return
def load_data(self, all_data):
self.handle_pair( 0, "", all_data)
return
def dump_file(self, filename):
with open(filename, 'w') as outfile:
json.dump(self.fields, outfile)
return
import sys
PARAMETERS_FILE = 'json_cli.txt'
if __name__ == "__main__":
from simple_parameters import simple_parameters
parser = simple_parameters.SimpleParser(PARAMETERS_FILE )
(options, args) = parser.resolve_parameters(sys.argv)
print(options.file)
temp = json_cli()
if options.file:
temp.load_file(options.file)
else:
temp.load_file("samples/basic.txt")
input()