将 shell 字符串可靠地转换为有效的 JSON 字符串的最佳选择是使用 JSON 解析器/格式化程序。最受欢迎的是jq。
这是一个使用 jq 的带时间戳的 JSON 消息记录器的实现:
#!/usr/bin/env bash
json_logger() {
while read -r msg || [ -n "$msg" ]; do
jq \
-nc \
--arg msg "$msg" \
'{ "timestamp": (now | strftime("%Y-%m-%d %H:%M:%S")), "message": $msg }'
done
}
----------
编辑:
正如KamilCuk 写道:
我们可以在没有缓慢的 bash 循环的情况下做得更好 - 它只是 jq --raw-input '{ "timestamp": (now | strftime("%Y-%m-%d %H:%M:%S")), "message": . }'
所以这里有一个改进的json_logger:
json_logger() {
jq \
--raw-input \
--compact-output \
'{ "timestamp": (now | strftime("%Y-%m-%d %H:%M:%S")), "message": . }'
}
附录:
Harshit Kushwaha wrote:
例如,我需要在调用 json_logger 的 json 中打印方法名称。如何修改 json_logger 以及如何在 echo 中使用它?
如果将方法名称作为参数提供给json_logger 函数,则下面是一个实现:
#!/usr/bin/env bash
IFS= read -r -d '' __JQ_LOGGER_SCRIPT <<'JQSCRIPT'
{
"timestamp": now | strftime("%Y-%m-%d %H:%M:%S"),
"message": .
} |
if ($name | length) != 0
then
. + { "method": $name }
else
.
end
JQSCRIPT
json_logger() {
jq \
--raw-input \
--compact-output \
--arg name "$1" \
"$__JQ_LOGGER_SCRIPT"
}
echo "I want to be a json message!" | json_logger
echo "I also want to be a json message!" | json_logger echo
printf %s $'I am a message with "quoted text" and some special characters: \'\t\7\42\\\'; that can only be properly converted to JSON with a JSON formatter and parser.' | json_logger printf
生成此 JSON 输出:
{"timestamp":"2021-01-29 14:02:46","message":"I want to be a json message!"}
{"timestamp":"2021-01-29 14:02:46","message":"I also want to be a json message!","method":"echo"}
{"timestamp":"2021-01-29 14:02:46","message":"I am a message with \"quoted text\" and some special characters: '\t\u0007\"\\'; that can only be properly converted to JSON with a JSON formatter and parser.","method":"printf"}