Skip to content

Instantly share code, notes, and snippets.

@stg7
Created November 6, 2016 01:32
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 stg7/be37daa88cfcc87a9b0fe3b3909a9d5e to your computer and use it in GitHub Desktop.
Save stg7/be37daa88cfcc87a9b0fe3b3909a9d5e to your computer and use it in GitHub Desktop.
Extract json subelements via command line and printout results on stdout.
#!/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