Fix Flake8 errors
[integration/test.git] / csit / libraries / backuprestore / jsonpathl.py
1 """
2 An XPath for JSON
3
4 A port of the Perl, and JavaScript versions of JSONPath
5 see http://goessner.net/articles/JsonPath/
6
7 Based on on JavaScript version by Stefan Goessner at:
8         http://code.google.com/p/jsonpath/
9 and Perl version by Kate Rhodes at:
10         http://github.com/masukomi/jsonpath-perl/tree/master
11 """
12
13 import re
14 import sys
15
16 __author__ = "Phil Budne"
17 __revision__ = "$Revision: 1.13 $"
18 __version__ = '0.54'
19
20 #   Copyright (c) 2007 Stefan Goessner (goessner.net)
21 #       Copyright (c) 2008 Kate Rhodes (masukomi.org)
22 #       Copyright (c) 2008-2012 Philip Budne (ultimate.com)
23 #   Licensed under the MIT licence:
24 #
25 #   Permission is hereby granted, free of charge, to any person
26 #   obtaining a copy of this software and associated documentation
27 #   files (the "Software"), to deal in the Software without
28 #   restriction, including without limitation the rights to use,
29 #   copy, modify, merge, publish, distribute, sublicense, and/or sell
30 #   copies of the Software, and to permit persons to whom the
31 #   Software is furnished to do so, subject to the following
32 #   conditions:
33 #
34 #   The above copyright notice and this permission notice shall be
35 #   included in all copies or substantial portions of the Software.
36 #
37 #   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
38 #   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
39 #   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
40 #   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
41 #   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
42 #   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
43 #   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
44 #   OTHER DEALINGS IN THE SOFTWARE.
45
46 # XXX BUGS:
47 # evalx is generally a crock:
48 #       handle !@.name.name???
49 # there are probably myriad unexpected ways to get an exception:
50 #       wrap initial "trace" call in jsonpath body in a try/except??
51
52 # XXX TODO:
53 # internally keep paths as lists to preserve integer types
54 #       (instead of as ';' delimited strings)
55
56 __all__ = ['jsonpath']
57
58
59 # XXX precompile RE objects on load???
60 # re_1 = re.compile(.....)
61 # re_2 = re.compile(.....)
62
63 def normalize(x):
64     """normalize the path expression; outside jsonpath to allow testing"""
65     subx = []
66
67     # replace index/filter expressions with placeholders
68     # Python anonymous functions (lambdas) are cryptic, hard to debug
69     def f1(m):
70         n = len(subx)  # before append
71         g1 = m.group(1)
72         subx.append(g1)
73         ret = "[#%d]" % n
74         return ret
75
76     x = re.sub(r"[\['](\??\(.*?\))[\]']", f1, x)
77
78     # added the negative lookbehind -krhodes
79     x = re.sub(r"'?(?<!@)\.'?|\['?", ";", x)
80
81     x = re.sub(r";;;|;;", ";..;", x)
82
83     x = re.sub(r";$|'?\]|'$", "", x)
84
85     # put expressions back
86     def f2(m):
87         g1 = m.group(1)
88         return subx[int(g1)]
89
90     x = re.sub(r"#([0-9]+)", f2, x)
91
92     return x
93
94
95 def jsonpath(obj, expr, result_type='VALUE', debug=0, use_eval=True):
96     """traverse JSON object using jsonpath expr, returning values or paths"""
97
98     def s(x, y):
99         """concatenate path elements"""
100         return str(x) + ';' + str(y)
101
102     def isint(x):
103         """check if argument represents a decimal integer"""
104         return x.isdigit()
105
106     def as_path(path):
107         """convert internal path representation to
108            "full bracket notation" for PATH output"""
109         p = '$'
110         for piece in path.split(';')[1:]:
111             # make a guess on how to index
112             # XXX need to apply \ quoting on '!!
113             if isint(piece):
114                 p += "[%s]" % piece
115             else:
116                 p += "['%s']" % piece
117         return p
118
119     def store(path, object):
120         if result_type == 'VALUE':
121             result.append(object)
122         elif result_type == 'IPATH':  # Index format path (Python ext)
123             # return list of list of indices -- can be used w/o "eval" or split
124             result.append(path.split(';')[1:])
125         else:  # PATH
126             result.append(as_path(path))
127         return path
128
129     def trace(expr, obj, path):
130         if debug:
131             print("trace", expr, "/", path)
132         if expr:
133             x = expr.split(';')
134             loc = x[0]
135             x = ';'.join(x[1:])
136             if debug:
137                 print("\t", loc, type(obj))
138             if loc == "*":
139                 def f03(key, loc, expr, obj, path):
140                     if debug > 1:
141                         print("\tf03", key, loc, expr, path)
142                     trace(s(key, expr), obj, path)
143
144                 walk(loc, x, obj, path, f03)
145             elif loc == "..":
146                 trace(x, obj, path)
147
148                 def f04(key, loc, expr, obj, path):
149                     if debug > 1:
150                         print("\tf04", key, loc, expr, path)
151                     if isinstance(obj, dict):
152                         if key in obj:
153                             trace(s('..', expr), obj[key], s(path, key))
154                     else:
155                         if key < len(obj):
156                             trace(s('..', expr), obj[key], s(path, key))
157
158                 walk(loc, x, obj, path, f04)
159             elif loc == "!":
160                 # Perl jsonpath extension: return keys
161                 def f06(key, loc, expr, obj, path):
162                     if isinstance(obj, dict):
163                         trace(expr, key, path)
164
165                 walk(loc, x, obj, path, f06)
166             elif isinstance(obj, dict) and loc in obj:
167                 trace(x, obj[loc], s(path, loc))
168             elif isinstance(obj, list) and isint(loc):
169                 iloc = int(loc)
170                 if len(obj) >= iloc:
171                     trace(x, obj[iloc], s(path, loc))
172             else:
173                 # [(index_expression)]
174                 if loc.startswith("(") and loc.endswith(")"):
175                     if debug > 1:
176                         print("index", loc)
177                     e = evalx(loc, obj)
178                     trace(s(e, x), obj, path)
179                     return
180
181                 # ?(filter_expression)
182                 if loc.startswith("?(") and loc.endswith(")"):
183                     if debug > 1:
184                         print("filter", loc)
185
186                     def f05(key, loc, expr, obj, path):
187                         if debug > 1:
188                             print("f05", key, loc, expr, path)
189                         if isinstance(obj, dict):
190                             eval_result = evalx(loc, obj[key])
191                         else:
192                             eval_result = evalx(loc, obj[int(key)])
193                         if eval_result:
194                             trace(s(key, expr), obj, path)
195
196                     loc = loc[2:-1]
197                     walk(loc, x, obj, path, f05)
198                     return
199
200                 m = re.match(r'(-?[0-9]*):(-?[0-9]*):?(-?[0-9]*)$', loc)
201                 if m:
202                     if isinstance(obj, (dict, list)):
203                         def max(x, y):
204                             if x > y:
205                                 return x
206                             return y
207
208                         def min(x, y):
209                             if x < y:
210                                 return x
211                             return y
212
213                         objlen = len(obj)
214                         s0 = m.group(1)
215                         s1 = m.group(2)
216                         s2 = m.group(3)
217
218                         # XXX int("badstr") raises exception
219                         start = int(s0) if s0 else 0
220                         end = int(s1) if s1 else objlen
221                         step = int(s2) if s2 else 1
222
223                         if start < 0:
224                             start = max(0, start + objlen)
225                         else:
226                             start = min(objlen, start)
227                         if end < 0:
228                             end = max(0, end + objlen)
229                         else:
230                             end = min(objlen, end)
231
232                         for i in xrange(start, end, step):
233                             trace(s(i, x), obj, path)
234                     return
235
236                 # after (expr) & ?(expr)
237                 if loc.find(",") >= 0:
238                     # [index,index....]
239                     for piece in re.split(r"'?,'?", loc):
240                         if debug > 1:
241                             print("piece", piece)
242                         trace(s(piece, x), obj, path)
243         else:
244             store(path, obj)
245
246     def walk(loc, expr, obj, path, funct):
247         if isinstance(obj, list):
248             for i in xrange(0, len(obj)):
249                 funct(i, loc, expr, obj, path)
250         elif isinstance(obj, dict):
251             for key in obj:
252                 funct(key, loc, expr, obj, path)
253
254     def evalx(loc, obj):
255         """eval expression"""
256
257         if debug:
258             print("evalx", loc)
259
260         # a nod to JavaScript. doesn't work for @.name.name.length
261         # Write len(@.name.name) instead!!!
262         loc = loc.replace("@.length", "len(__obj)")
263
264         loc = loc.replace("&&", " and ").replace("||", " or ")
265
266         # replace !@.name with 'name' not in obj
267         # XXX handle !@.name.name.name....
268         def notvar(m):
269             return "'%s' not in __obj" % m.group(1)
270
271         loc = re.sub("!@\.([a-zA-Z@_]+)", notvar, loc)
272
273         # replace @.name.... with __obj['name']....
274         # handle @.name[.name...].length
275         def varmatch(m):
276             def brackets(elts):
277                 ret = "__obj"
278                 for e in elts:
279                     if isint(e):
280                         ret += "[%s]" % e  # ain't necessarily so
281                     else:
282                         ret += "['%s']" % e  # XXX beware quotes!!!!
283                 return ret
284
285             g1 = m.group(1)
286             elts = g1.split('.')
287             if elts[-1] == "length":
288                 return "len(%s)" % brackets(elts[1:-1])
289             return brackets(elts[1:])
290
291         loc = re.sub(r'(?<!\\)(@\.[a-zA-Z@_.]+)', varmatch, loc)
292
293         # removed = -> == translation
294         # causes problems if a string contains =
295
296         # replace @  w/ "__obj", but \@ means a literal @
297         loc = re.sub(r'(?<!\\)@', "__obj", loc).replace(r'\@', '@')
298         if not use_eval:
299             if debug:
300                 print("eval disabled")
301             raise Exception("eval disabled")
302         if debug:
303             print("eval", loc)
304         try:
305             # eval w/ caller globals, w/ local "__obj"!
306             v = eval(loc, caller_globals, {'__obj': obj})
307         except Exception as e:
308             if debug:
309                 print(e)
310         return False
311
312         if debug:
313             print("->", v)
314         return v
315
316     # body of jsonpath()
317
318     # Get caller globals so eval can pick up user functions!!!
319     caller_globals = sys._getframe(1).f_globals
320     result = []
321     if expr and obj:
322         cleaned_expr = normalize(expr)
323         if cleaned_expr.startswith("$;"):
324             cleaned_expr = cleaned_expr[2:]
325
326         # XXX wrap this in a try??
327         trace(cleaned_expr, obj, '$')
328
329         if len(result) > 0:
330             return result
331     return False
332
333
334 if __name__ == '__main__':
335     try:
336         import json  # v2.6
337     except ImportError:
338         import simplejson as json
339
340     import sys
341
342     # XXX take options for output format, output file, debug level
343
344     if len(sys.argv) < 3 or len(sys.argv) > 4:
345         sys.stdout.write("Usage: jsonpath.py FILE PATH [OUTPUT_TYPE]\n")
346         sys.exit(1)
347
348     object = json.load(file(sys.argv[1]))
349     path = sys.argv[2]
350     format = 'VALUE'
351
352     if len(sys.argv) > 3:
353         # XXX verify?
354         format = sys.argv[3]
355
356     value = jsonpath(object, path, format)
357
358     if not value:
359         sys.exit(1)
360
361     f = sys.stdout
362     json.dump(value, f, sort_keys=True, indent=1)
363     f.write("\n")
364
365     sys.exit(0)