我目前正在练习将 纯文本转换为 csv,并将它们 csv 转换为 json。我只需要使用 jq 和基本的 Linux 命令来进行转换。
我在将纯文本转换为 csv 时没有遇到任何重大问题,但进一步转换有点棘手。主要是因为第一行和最后一行不符合标准。
这是我当前的 csv:
Asserts Samples
1;expecting command finishes successfully (bash exe);7ms
1;expecting command finishes successfully (loading bin, execute);27ms
0;expecting command fails (bash exe, execute);23ms
...
0;expecting command prints some message (bash exe);12ms
0;expecting command prints some message (loading bin, execute);26ms
5;2;71.43;136ms
我需要将此 csv 转换为以下格式:
{
"testName": "Asserts Samples",
"tests": [
{
"name": "expecting command finishes successfully (bash exe)",
"status": false,
"duration": "7ms"
},
...
{
"name": "expecting command prints some message (loading bin, execute)",
"status": true,
"duration": "26ms"
}
],
"summary": {
"success": 5,
"failed": 2,
"rating": 71.43,
"duration": "136ms"
}
}
到目前为止我已经弄清楚:
map({"name": .[1],...
select(.status == "0")).status |= true
(split(";")
长时间尝试未能制作出 json 结构具有相应的数组和对象结构。 我很乐意提供建议或指导。
您可以将
jq
与原始输入选项 (-R
) 和 -s
一起使用,将整个文件作为单个字符串并拆分为数组,然后您可以使用 $lines[1:-1]
访问测试行(因此我们跳过第一个) )。对于每条测试线,将其分割为 ";"
并将字段映射到所需的键。由于在您的数据中 "0"
代表测试成功(状态 true
),因此您可以使用 (.[0] == "0")
转换状态。然后处理最后一个摘要第一行(因此使用 -1
索引来获取它)。
结合起来应该会给你这个怪物:
jq -R -s '
(split("\n") | map(select(length > 0))) as $lines |
{
testName: $lines[0],
tests: ($lines[1:-1] | map(
(split(";") | {
name: .[1],
status: (.[0] == "0"),
duration: .[2]
})
)),
summary: ($lines[-1] | split(";") | {
success: (.[0] | tonumber),
failed: (.[1] | tonumber),
rating: (.[2] | tonumber),
duration: .[3]
})
}
' input.csv
一旦在输入数据上运行,输出应该是
{
"testName": "Asserts Samples",
"tests": [
{
"name": "expecting command finishes successfully (bash exe)",
"status": false,
"duration": "7ms"
},
{
"name": "expecting command finishes successfully (loading bin, execute)",
"status": false,
"duration": "27ms"
},
{
"name": "expecting command fails (bash exe, execute)",
"status": true,
"duration": "23ms"
},
{
"name": null,
"status": false,
"duration": null
},
{
"name": "expecting command prints some message (bash exe)",
"status": true,
"duration": "12ms"
},
{
"name": "expecting command prints some message (loading bin, execute)",
"status": true,
"duration": "26ms"
}
],
"summary": {
"success": 5,
"failed": 2,
"rating": 71.43,
"duration": "136ms"
}
}