4 A port of the Perl, and JavaScript versions of JSONPath
5 see http://goessner.net/articles/JsonPath/
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
16 __author__ = "Phil Budne"
17 __revision__ = "$Revision: 1.13 $"
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:
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
34 # The above copyright notice and this permission notice shall be
35 # included in all copies or substantial portions of the Software.
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.
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??
53 # internally keep paths as lists to preserve integer types
54 # (instead of as ';' delimited strings)
56 __all__ = ["jsonpath"]
59 # XXX precompile RE objects on load???
60 # re_1 = re.compile(.....)
61 # re_2 = re.compile(.....)
65 """normalize the path expression; outside jsonpath to allow testing"""
68 # replace index/filter expressions with placeholders
69 # Python anonymous functions (lambdas) are cryptic, hard to debug
71 n = len(subx) # before append
77 x = re.sub(r"[\['](\??\(.*?\))[\]']", f1, x)
79 # added the negative lookbehind -krhodes
80 x = re.sub(r"'?(?<!@)\.'?|\['?", ";", x)
82 x = re.sub(r";;;|;;", ";..;", x)
84 x = re.sub(r";$|'?\]|'$", "", x)
86 # put expressions back
91 x = re.sub(r"#([0-9]+)", f2, x)
96 def jsonpath(obj, expr, result_type="VALUE", debug=0, use_eval=True):
97 """traverse JSON object using jsonpath expr, returning values or paths"""
100 """concatenate path elements"""
101 return str(x) + ";" + str(y)
104 """check if argument represents a decimal integer"""
108 """convert internal path representation to
109 "full bracket notation" for PATH output"""
111 for piece in path.split(";")[1:]:
112 # make a guess on how to index
113 # XXX need to apply \ quoting on '!!
117 p += "['%s']" % piece
120 def store(path, object):
121 if result_type == "VALUE":
122 result.append(object)
123 elif result_type == "IPATH": # Index format path (Python ext)
124 # return list of list of indices -- can be used w/o "eval" or split
125 result.append(path.split(";")[1:])
127 result.append(as_path(path))
130 def trace(expr, obj, path):
132 print("trace", expr, "/", path)
138 print("\t", loc, type(obj))
141 def f03(key, loc, expr, obj, path):
143 print("\tf03", key, loc, expr, path)
144 trace(s(key, expr), obj, path)
146 walk(loc, x, obj, path, f03)
150 def f04(key, loc, expr, obj, path):
152 print("\tf04", key, loc, expr, path)
153 if isinstance(obj, dict):
155 trace(s("..", expr), obj[key], s(path, key))
158 trace(s("..", expr), obj[key], s(path, key))
160 walk(loc, x, obj, path, f04)
162 # Perl jsonpath extension: return keys
163 def f06(key, loc, expr, obj, path):
164 if isinstance(obj, dict):
165 trace(expr, key, path)
167 walk(loc, x, obj, path, f06)
168 elif isinstance(obj, dict) and loc in obj:
169 trace(x, obj[loc], s(path, loc))
170 elif isinstance(obj, list) and isint(loc):
173 trace(x, obj[iloc], s(path, loc))
175 # [(index_expression)]
176 if loc.startswith("(") and loc.endswith(")"):
180 trace(s(e, x), obj, path)
183 # ?(filter_expression)
184 if loc.startswith("?(") and loc.endswith(")"):
188 def f05(key, loc, expr, obj, path):
190 print("f05", key, loc, expr, path)
191 if isinstance(obj, dict):
192 eval_result = evalx(loc, obj[key])
194 eval_result = evalx(loc, obj[int(key)])
196 trace(s(key, expr), obj, path)
199 walk(loc, x, obj, path, f05)
202 m = re.match(r"(-?[0-9]*):(-?[0-9]*):?(-?[0-9]*)$", loc)
204 if isinstance(obj, (dict, list)):
221 # XXX int("badstr") raises exception
222 start = int(s0) if s0 else 0
223 end = int(s1) if s1 else objlen
224 step = int(s2) if s2 else 1
227 start = max(0, start + objlen)
229 start = min(objlen, start)
231 end = max(0, end + objlen)
233 end = min(objlen, end)
235 for i in xrange(start, end, step):
236 trace(s(i, x), obj, path)
239 # after (expr) & ?(expr)
240 if loc.find(",") >= 0:
242 for piece in re.split(r"'?,'?", loc):
244 print("piece", piece)
245 trace(s(piece, x), obj, path)
249 def walk(loc, expr, obj, path, funct):
250 if isinstance(obj, list):
251 for i in xrange(0, len(obj)):
252 funct(i, loc, expr, obj, path)
253 elif isinstance(obj, dict):
255 funct(key, loc, expr, obj, path)
258 """eval expression"""
263 # a nod to JavaScript. doesn't work for @.name.name.length
264 # Write len(@.name.name) instead!!!
265 loc = loc.replace("@.length", "len(__obj)")
267 loc = loc.replace("&&", " and ").replace("||", " or ")
269 # replace !@.name with 'name' not in obj
270 # XXX handle !@.name.name.name....
272 return "'%s' not in __obj" % m.group(1)
274 loc = re.sub("!@\.([a-zA-Z@_]+)", notvar, loc)
276 # replace @.name.... with __obj['name']....
277 # handle @.name[.name...].length
283 ret += "[%s]" % e # ain't necessarily so
285 ret += "['%s']" % e # XXX beware quotes!!!!
290 if elts[-1] == "length":
291 return "len(%s)" % brackets(elts[1:-1])
292 return brackets(elts[1:])
294 loc = re.sub(r"(?<!\\)(@\.[a-zA-Z@_.]+)", varmatch, loc)
296 # removed = -> == translation
297 # causes problems if a string contains =
299 # replace @ w/ "__obj", but \@ means a literal @
300 loc = re.sub(r"(?<!\\)@", "__obj", loc).replace(r"\@", "@")
303 print("eval disabled")
304 raise Exception("eval disabled")
308 # eval w/ caller globals, w/ local "__obj"!
309 v = eval(loc, caller_globals, {"__obj": obj})
310 except Exception as e:
321 # Get caller globals so eval can pick up user functions!!!
322 caller_globals = sys._getframe(1).f_globals
325 cleaned_expr = normalize(expr)
326 if cleaned_expr.startswith("$;"):
327 cleaned_expr = cleaned_expr[2:]
329 # XXX wrap this in a try??
330 trace(cleaned_expr, obj, "$")
337 if __name__ == "__main__":
341 import simplejson as json
345 # XXX take options for output format, output file, debug level
347 if len(sys.argv) < 3 or len(sys.argv) > 4:
348 sys.stdout.write("Usage: jsonpath.py FILE PATH [OUTPUT_TYPE]\n")
351 object = json.load(file(sys.argv[1]))
355 if len(sys.argv) > 3:
359 value = jsonpath(object, path, format)
365 json.dump(value, f, sort_keys=True, indent=1)