Skip to content

Instantly share code, notes, and snippets.

@bhyde
Created August 10, 2015 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhyde/6778be7181a5e53af108 to your computer and use it in GitHub Desktop.
Save bhyde/6778be7181a5e53af108 to your computer and use it in GitHub Desktop.
A python implementation of https://github.com/jmespath/jp
#!/bin/env python
"""
USAGE: jpsearch [--unquoted|-u] [-f|--filename <json-file>] <JMESPath>
Reads json from standard input, or the file
if given. Then searches that as instructed
by the JMESPath; and prints the result. If
the result is a string and --unquoted is given
the string is printed without quotation. See
also http://jmespath.org/
"""
from __future__ import print_function
from sys import stdin, stderr, argv
from json import load, dumps
from jmespath import search
def usage_and_exit():
print(__doc__)
exit(0)
def parse_args():
n = len(argv)
if (n < 2) or (5 < n):
print("foo")
usage_and_exit()
unquoted = False
input = stdin
i = [0]
def next_arg():
i[0] += 1
if i[0] >= n:
Exception("Exausted args unexpectedly")
return argv[i[0]]
while True:
if i[0] + 1 >= n:
break
a = next_arg()
if a == '-u' or a == '--unquoted':
unquoted = True
elif a == '-f' or a == '--filename':
input = open(next_arg())
elif a == '-h' or a == '--help':
print('bar ' + a)
usage_and_exit()
elif a.startswith('-'):
usage_and_exit()
else:
path = a
return (unquoted, input, path)
def main():
(unquoted, input, path) = parse_args()
try:
json = load(input)
except Exception as e:
print("Unable to parse json: %s" % str(e), file=stderr)
exit(1)
result = search(path, json)
if unquoted and isinstance(result, basestring):
print(result)
else:
print(dumps(result, sort_keys=True, indent=2))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment