Skip to content

Instantly share code, notes, and snippets.

@h8rt3rmin8r
Last active June 16, 2020 06:38
Show Gist options
  • Save h8rt3rmin8r/70d68afed53b2cbb93b8660a823fcb56 to your computer and use it in GitHub Desktop.
Save h8rt3rmin8r/70d68afed53b2cbb93b8660a823fcb56 to your computer and use it in GitHub Desktop.
Generate JSON objects filled with custom keys and values
#! /usr/bin/env bash
#
# [ build-json-object.sh ]
#
# Generate JSON objects filled with custom keys and values
# Created on 20200616 by h8rt3rmin8r
#
## Declare variables
_ak=$'\u002A'
_co=$'\u003A'
_ds=$'\u002D'
_q1=$'\u0027'
_q2=$'\u0022'
_sp=$'\u0020'
_cba=$'\u007B'
_cbb=$'\u007D'
_usd=$'\u0024'
arg_a=""
arg_b=""
n_x=1
## Parse user inputs
if [[ "x${1}" == "x" || "${1}" == "-h" || "${1}" =~ ^[-]+help$ ]]; then
echo "Usage: --key=value ... --key=value"
exit 0
fi
while [[ "$#" -gt 0 ]]; do
if [[ ! "${1}" =~ "=" ]]; then
echo "ERROR: Improperly formatted 'key=value' syntax detected"
exit 1
fi
key_a="${1//[=]*}"
key_b="${key_a#[-]}"
key_c="${key_b#[-]}"
key="${key_c// /_}"
val_a="${1//*[=]}"
val="${val_a//[\'\"]}"
if [[ "x${key}" == "x" || "${val}" == "x" ]]; then
echo "ERROR: Improperly formatted 'key=value' syntax detected"
exit 1
fi
x_x="x${n_x}x"
arg_a="${arg_a}${_ds}${_ds}arg${_sp}${x_x}${_sp}${_q2}${val}${_q2}${_sp}"
arg_b="${arg_b}${key}${_co}${_usd}${x_x},"
let n_x=n_x+1
shift 1
done
arg_b="${arg_b%,}"
cmd_x="jq${_sp}${arg_a}${_q1}.${_ak}${_cba}${arg_b}${_cbb}${_q1}${_sp}<<<${_q1}${_cba}${_cbb}${_q1}"
cmd_y="jq${_sp}${arg_a}${_q1}.${_ak}${_cba}${arg_b}${_cbb}${_q1}"
if [ -t 0 ]; then
eval ${cmd_x}
else
eval ${cmd_y}
fi
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment