Last active
February 25, 2022 17:25
-
-
Save johnstanfield/2940fe8edf0c5f865cb4d138ba27669b to your computer and use it in GitHub Desktop.
jqsay -- turn bash args into json
This file contains 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
#!/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