Created
November 6, 2016 01:32
-
-
Save stg7/be37daa88cfcc87a9b0fe3b3909a9d5e to your computer and use it in GitHub Desktop.
Extract json subelements via command line and printout results on stdout.
This file contains 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 | |
""" | |
Extract json subelements via command line and printout results on stdout. | |
Example call: | |
echo "{\"a\":100, \"b\": [1,2,3]}" | ./json_extractor.py b | |
will print: | |
[ | |
1, | |
2, | |
3 | |
] | |
""" | |
import json | |
import sys | |
def is_int(x): | |
""" check if x is an integer """ | |
try: | |
xi = int(x) | |
return True | |
except Exception: | |
return False | |
obj = "" | |
for l in sys.stdin: | |
obj += l | |
try: | |
j = json.loads(obj) | |
for i in sys.argv[1:]: | |
if is_int(i): | |
# for array access convert parameter to int | |
j = j[int(i)] | |
else: | |
j = j[i] | |
print(json.dumps(j, indent=4, sort_keys=True)) | |
except Exception as e: | |
print('error: ' + str(e), file=sys.stderr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment