Skip to content

Commit 57c84c0

Browse files
committed
add jsonpath.py script based on https://github.com/makefu/jsonpath (but improved and expanded) that will be installed in bin/. this means anyone installing this package will also get a jsonpath.py that will work on the command line
1 parent f4cfe56 commit 57c84c0

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

jsonpath_rw/bin/jsonpath.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#!/usr/bin/python
2+
# encoding: utf-8
3+
# Copyright © 2012 Felix Richter <wtfpl@syntax-fehler.de>
4+
# This work is free. You can redistribute it and/or modify it under the
5+
# terms of the Do What The Fuck You Want To Public License, Version 2,
6+
# as published by Sam Hocevar. See the COPYING file for more details.
7+
8+
from jsonpath_rw import parse
9+
import json
10+
import sys
11+
import glob
12+
if len(sys.argv) < 2:
13+
print("""usage: %s jsonpath [files]
14+
path can be:
15+
atomics:
16+
$ - root object
17+
`this` - current object
18+
19+
operators:
20+
path1.path2 - same as xpath /
21+
path1|path2 - union
22+
path1..path2 - somewhere in between
23+
24+
fiels:
25+
fieldname - field with name
26+
* - any field
27+
[_start_?:_end_?] - array slice
28+
[*] - any array index
29+
""")
30+
sys.exit(1)
31+
32+
expr = parse(sys.argv[1])
33+
34+
def find_matches_for_file(f):
35+
return [unicode(match.value) for match in expr.find(json.load(f))]
36+
37+
def print_matches(matches):
38+
print(u"\n".join(matches).encode("utf-8"))
39+
40+
if len(sys.argv) < 3:
41+
# stdin mode
42+
print_matches(find_matches_for_file(sys.stdin))
43+
else:
44+
# file paths mode
45+
for pattern in sys.argv[2:]:
46+
for filename in glob.glob(pattern):
47+
with open(filename) as f:
48+
print_matches(find_matches_for_file(f))
49+

setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
license='Apache 2.0',
1515
long_description=io.open('README.rst', encoding='utf-8').read(),
1616
packages = ['jsonpath_rw'],
17+
scripts = ['jsonpath_rw/bin/jsonpath.py'],
1718
test_suite = 'tests',
1819
install_requires = [ 'ply', 'decorator', 'six' ],
1920
classifiers = [

0 commit comments

Comments
 (0)