Skip to content

Instantly share code, notes, and snippets.

@johnstanfield
Last active February 25, 2022 17:25
Show Gist options
  • Save johnstanfield/2940fe8edf0c5f865cb4d138ba27669b to your computer and use it in GitHub Desktop.
Save johnstanfield/2940fe8edf0c5f865cb4d138ba27669b to your computer and use it in GitHub Desktop.
jqsay -- turn bash args into json
#!/usr/bin/env bash
# jq-say
# format string as JSON message
#
# treat odd args as keys and even args as values
# use jq to output something like this, for as many args supplied:
# {"arg1": "arg2", "arg3": "arg4"}
#
# very helpful for echo'ing log messages as JSON
#
# ymmv if you don't use bash or if you supply and odd number of args or no args at all
#
# examples
# jqsay foo bar baz bat
# {
# "foo": "bar",
# "baz": "bat"
# }
#
# jqsay source myapp severity 3 human-readable "bla bla bla message" action restart
# {
# "source": "myapp",
# "severity": "3",
# "human-readable": "bla bla bla message",
# "action": "restart"
# }
jqsay(){
cmd=(jq -c --null-input)
jsony=""
for i in `seq 1 2 $#`; do
n=$((i+1))
cmd+=("--arg \""arg${i}\"" \""${!n}"\"")
jsony="${jsony}\"${!i}\": \$arg${i},"
done
cmd+=("'{${jsony::-1}}'")
eval ${cmd[@]}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment