Last active
August 29, 2015 14:17
-
-
Save NickLaMuro/c3b2829d0ae807c78119 to your computer and use it in GitHub Desktop.
Bash aliases/functions for parsing and viewing json
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
# Pretty print json in the terminal like so: | |
# $ echo "{'json': 'stuff'}" | json | |
alias json='python -mjson.tool' | |
# Parses json. Each arg is a level deeper in the tree: | |
# | |
# Examples | |
# | |
# echo "{'json': {'foo': 'bar'}}" | parse_json | |
# => {'json': {'foo': 'bar'}} | |
# | |
# echo "{'foo': {'bar': 'baz'}}" | parse_json foo | |
# => {'bar': 'baz'} | |
# | |
# echo "{'foo': [{'bar': 'baz'}}]" | parse_json foo [0] | |
# => {'foo': 'bar'} | |
# | |
parse_json() { | |
python -c "import json,sys;print json.dumps(json.load(sys.stdin)$(__process_json_args_for_use_in_parsing "$*"))" | |
} | |
# Parses json and returns the keys as a list. | |
# | |
# Examples | |
# | |
# $ echo "{'json': {'foo': 'bar'}}" | parse_json_keys | |
# => json | |
# | |
# $ echo "{'foo': {'bar': 'baz'}}" | parse_json_keys foo | |
# => bar | |
# | |
# $ echo "{'foo': [{'bar': 'baz'}}]" | parse_json_keys foo [0] | |
# => bar | |
# | |
parse_json_keys() { | |
python -c "import json,sys;print \"\\n\".join(json.load(sys.stdin)$(__process_json_args_for_use_in_parsing "$*").keys());" | |
} | |
# Parses arguments for use with parse_json and parse_json_keys | |
# | |
# Examples | |
# | |
# $ __process_json_args_for_use_in_parsing foo | |
# => ['foo'] | |
# | |
# $ __process_json_args_for_use_in_parsing foo bar | |
# => ['foo']['bar'] | |
# | |
# $ __process_json_args_for_use_in_parsing foo [0] bar | |
# => ['foo'][0]['bar'] | |
# | |
__process_json_args_for_use_in_parsing() { | |
output='' | |
for var in $*; do | |
if [[ $var =~ ^\[[0-9]*\]$ ]]; then | |
output="$output$var" | |
else | |
output="$output['$var']" | |
fi | |
done | |
printf "$output" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment