如何将这些文本字符串列表转换为json
文字字符串:
start filelist:
/download/2017/download_2017.sh
/download/2017/log_download_2017.json
/download/2017/log_download_2017.txt
start wget:
2017-05-15 20:42:00 URL:http://web.site.com/downloads/2017/file_1.zip [1024/1024] -> "file_1.zip" [1]
2017-05-15 20:43:21 URL:http://web.site.com/downloads/2017/file_2.zip [2048/2048] -> "file_2.zip" [1]
JSON输出:
{
"start filelist": [
"download_2017.sh",
"log_download_2017.txt",
"log_download_2017.json",
],
}
{
"start wget": [
"2017-05-15 20:43:01 URL:http://web.site.com/downloads/2017/file_1.zip [1024/1024] -> "file_1.zip" [1]",
"2017-05-15 20:43:21 URL:http://web.site.com/downloads/2017/file_2.zip [2048/2048] -> "file_2.zip" [1]",
],
}
欣赏任何选择和方法
答案 0 :(得分:1)
这是一个仅限jq的解决方案,它会根据您的示例生成有效的JSON:
foreach (inputs,null) as $line ({};
if $line == null then .emit = {(.key): .value}
elif $line[-1:] == ":"
then (if .key then {emit: {(.key): .value}} else null end)
+ { key : $line[0:-1] }
else {key, value: (.value + [$line])}
end;
.emit // empty )
调用:
jq -n -R -f program.jq input.txt
请特别注意-n选项。
如果输入不是以"键开头,那么#34;行,然后上面的jq程序将报告错误并终止。如果需要更多容错,则可能会对以下变量感兴趣:
foreach (inputs,null) as $line ({};
if $line == null then .emit = {(.key|tostring): .value}
elif $line[-1:] == ":"
then (if .key then {emit: {(.key): .value}} else null end)
+ { key : $line[0:-1] }
else {key, value: (.value + [$line])}
end;
.emit // empty )