Last active
August 29, 2015 14:13
-
-
Save ddksr/c712195a907cbabb2f30 to your computer and use it in GitHub Desktop.
Script for parsing jsons in bash
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
#!/bin/python | |
""" | |
pjson - simple script for parsing jsons with python | |
Json input needed with stdin. | |
Usage: | |
pjson key1 key2 key3 ... | |
Examples: | |
$ echo '{ "articles": [ { "title": "Title 1" }, { "title": "Title 3" }, { "title": "Title 3" } ]}' | pjson | |
{ | |
"articles": [ | |
{ | |
"title": "Title 1" | |
}, | |
{ | |
"title": "Title 3" | |
}, | |
{ | |
"title": "Title 3" | |
} | |
] | |
} | |
$ echo '{ "articles": [ { "title": "Title 1" }, { "title": "Title 3" }, { "title": "Title 3" } ]}' | pjson articles [12:10:08] | |
[ | |
{ | |
"title": "Title 1" | |
}, | |
{ | |
"title": "Title 3" | |
}, | |
{ | |
"title": "Title 3" | |
} | |
] | |
echo '{ "articles": [ { "title": "Title 1" }, { "title": "Title 3" }, { "title": "Title 3" } ]}' | pjson articles 0 [12:10:30] | |
{ | |
"title": "Title 1" | |
} | |
$ echo '{ "articles": [ { "title": "Title 1" }, { "title": "Title 3" }, { "title": "Title 3" } ]}' | pjson articles 0 title [12:10:49] | |
"Title 1" | |
$ echo '{ "articles": [ { "title": "Title 1" }, { "title": "Title 3" }, { "title": "Title 3" } ]}' | pjson articles ... title [12:11:02] | |
[ | |
"Title 1", | |
"Title 3", | |
"Title 3" | |
] | |
""" | |
import sys,json | |
def main(): | |
json_obj = json.load(sys.stdin) | |
select_all = False | |
for arg in sys.argv[1:]: | |
if not select_all and isinstance(json_obj, (list, tuple, str, set, )): | |
if arg != '...': | |
json_obj = json_obj[int(arg)] | |
else: | |
select_all = True | |
else: | |
if select_all: | |
json_obj = [ | |
obj[arg] for obj in json_obj | |
] | |
select_all = False | |
else: | |
json_obj = json_obj[arg] | |
print(json.dumps(json_obj, sort_keys=True, indent=4)) | |
try: | |
main() | |
except KeyboardInterrupt: | |
print(__doc__) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment