jq将两个文本字符串转换为单独的json对象

时间:2017-05-15 05:45:34

标签: json bash sh text-processing jq

如何将这两个文本字符串转换为单独的json对象

文字字符串:

start process: Mon May 15 03:14:09 UTC 2017
logfilename: log_download_2017

Json输出:

{
"start process": "Mon May 15 03:14:09 UTC 2017",
}
{
"logfilename": "log_download_2017",
}

Shell脚本:

logfilename="log_download_2017"
echo "start process: $(date -u)" | tee -a $logfilename.txt | jq -R split(:) >> $logfilename.json
echo "logfilename:" $logfilename | tee -a $logfilename.txt | jq -R split(:) >> $logfilename.json

1 个答案:

答案 0 :(得分:1)

一种方法是使用index/1,例如沿着这些方向:

jq -R 'index(":") as $ix | {(.[:$ix]) : .[$ix+1:]}'

或者,如果你的jq支持正则表达式,你可能会考虑:

jq -R 'match( "([^:]*):(.*)" ) | .captures | {(.[0].string): .[1].string}'

或:

jq -R '[capture( "(?<key>[^:]*):(?<value>.*)" )] | from_entries'