Last active
November 28, 2018 00:18
-
-
Save bitdivine/bc79449b56a89ee0e7c99fc8963dc271 to your computer and use it in GitHub Desktop.
A command line jmespath filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import sys | |
| import json | |
| import jmespath | |
| import argparse | |
| parser = argparse.ArgumentParser(description='Apply a jmespath filter to stdin') | |
| parser.add_argument('jmespath', metavar='JMESPATH', type=str, nargs=1, | |
| help='jmespath expression') | |
| parser.add_argument('--output', dest='output_format', action='store', | |
| default='json', | |
| help='the output format: text or pretty or json') | |
| args = parser.parse_args() | |
| path = sys.argv[1] | |
| data = json.load(sys.stdin) | |
| ans = jmespath.search(path, data) | |
| if args.output_format in ['text','txt']: | |
| if isinstance(ans, list): | |
| for line in ans: | |
| print(line) | |
| else: | |
| print(ans) | |
| elif args.output_format in ['pretty']: | |
| print(json.dumps(ans, indent=2, sort_keys=True)) | |
| else: | |
| print(json.dumps(ans)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment