Skip to content

Instantly share code, notes, and snippets.

@hendrikb
Created April 9, 2015 13:39
Show Gist options
  • Save hendrikb/10fd950a223939b6e6dd to your computer and use it in GitHub Desktop.
Save hendrikb/10fd950a223939b6e6dd to your computer and use it in GitHub Desktop.
jsonify turns command line arguments into full featured JSON documents
#!/bin/bash
# This tool turns command line arguments into full featured JSON documents
# author: Hendrik Bergunde <hbergunde@gmx.de> https://gist.github.com/hendrikb/
# Call jsonify --help for help
# Put this script somewhere into your $PATH variable to access it from anywhere
# Thanks for using this script - I love you all.
# useful functions
function usage() {
echo 'jsonify <--[json-key-name] [json value] ... | OPTIONS>'
echo
echo ' jsonify takes --command-line-arguments and values and renders them as'
echo ' a JSON document. :)'
echo
echo ' You need at least one pair of --json-key-name json-value which then'
echo " will be rendered into {'json-key-name': 'json-value'} "
echo
echo 'Options:'
echo ' -p pretty print the output'
echo " -t add @timestamp field in the format `date '+%FT%R:%S%:z'`"
echo ' -h show this help'
}
function fail() {
echo $1 1>&2
echo
exit $2
}
function argument_to_key() {
echo $1 | sed -e 's/^--//'
}
function parse_flag() {
echo $1 | sed -e 's/^-//'
}
function print() {
if [ $PRETTY == true ] ; then
echo $@
else
echo -n $@
fi
}
###### Validation of Arguments ########
if [ "$1" == "--help" ] || [ "$1" == "-h" ] ; then usage ; exit 0 ; fi
if [ -z "$1" ] || [ -z "$2" ] ; then fail 'You need at least two parameters!' 1 ; fi
if [[ $1 =~ ^[a-z] ]] ; then fail 'You need to specify at least one --argument' 2; fi
SHOW_TIMESTAMP=false
PRETTY=false
###### Parsing of Arguments ########
JSON_KEY_VALUES=()
while [ ! -z "$1" ] ; do
if [[ $1 =~ ^--.+ ]] ; then
if [[ $1 =~ = ]] ; then fail "Sorry, we do not support --keyname=value notation. Please use --keyname value :)" 4 ; fi
if [ -z "$2" ] ; then fail "Missing value argument for $1 - aborting" 3 ; fi
JSON_KEY_VALUES+=("\"`argument_to_key $1`\": \"$2\"")
shift 2
else
if [[ $1 =~ ^-.+ ]] ; then
flag=`parse_flag $1`
if [ "$flag" == "p" ] ; then PRETTY=true ; fi
if [ "$flag" == "t" ] ; then SHOW_TIMESTAMP=true ; fi
shift 1
else
fail "Don't know what to do with argument \"$1\" - please call for --help" 99 ;
fi
fi
done
###### Output ########
TIMESTAMP=`date "+%FT%R:%S%:z"`
i=0
print '{'
for row in "${JSON_KEY_VALUES[@]}"
do
if [ $PRETTY == true ] ; then echo -en "\t" ; fi
echo -n $row
i=$((i+1))
if [ ! $i -eq ${#JSON_KEY_VALUES[@]} ] || [ $SHOW_TIMESTAMP == true ] ; then echo -n ', ' ; fi
if [ $PRETTY == true ] ; then echo; fi
done
if [ $SHOW_TIMESTAMP == true ] ; then
if [ $PRETTY == true ] ; then echo -en "\t" ; fi
echo -n "\"@timestamp\": \"$TIMESTAMP\""
if [ $PRETTY == true ] ; then echo; fi
fi
echo '}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment