I wrote this little script to extract a specific JSON field passed in from command line. It works and all but it seems inefficient. Any suggestion on any improvement?
jsonx.py name jdoe.json will return "John Doe" jsonx.py rec.course jdoe.json will return "Java"
#!/usr/bin/env python
import sys
import re
import json
def main():
sys.tracebacklimit = 0
argc = len(sys.argv)
if argc == 2:
field = sys.argv[1]
infile = sys.stdin
elif argc == 3:
field = sys.argv[1]
infile = open(sys.argv[2], 'rb')
else:
raise SystemExit(sys.argv[0] + " <json-field> [ <json-file> ]")
with infile:
try:
obj = json.load(infile)
except(ValueError, e):
raise SystemExit(e)
for f in [f for f in re.split("[\.\[\]]", field) if f != '']:
try:
if f.isdigit():
obj = obj[int(f)]
else:
obj = obj[f]
except(ValueError, e):
raise SystemExit(e)
print(obj)
if __name__ == '__main__':
main()
Sample json file:
{
"name": "John Doe",
"rec": {
"id": 1,
"course": "Java"
}
}
jsonx.py name jdoe.json will return "John Doe"?nameattribute fromjdoe.json