导出到 CSV 时如何不让 jq 解释换行符
How to not let jq interpret the newline character when exporting to CSV
我要转换存储在文件中的以下JSON内容tmp.json
{
"results": [
[
{
"field": "field1",
"value": "value1-1"
},
{
"field": "field2",
"value": "value1-2\n"
}
],
[
{
"field": "field1",
"value": "value2-1"
},
{
"field": "field2",
"value": "value2-2\n"
}
]
]
}
转换为 CSV 输出
"field1","field2"
"value1-1","value1-2\n"
"value2-1","value2-2\n"
然而,当我使用此 jq
命令时,
cat tmp.json | jq -r '.results | (first | map(.field)), (.[] | map(.value)) | @csv'
我得到这个结果:
"field1","field2"
"value1-1","value1-2
"
"value2-1","value2-2
"
应该如何编写 jq
命令以获得所需的 CSV 结果?
如果换行符是您唯一可以处理的,也许您可以进行字符串替换。
cat tmp.json | jq -r '.results | (first | map(.field)), (.[] | map(.value) | map(gsub("\n"; "\n"))) | @csv'
对于仅 jq 的解决方案,您可以使用 gsub("\n"; "\n")
。我会选择这样的东西:
.results
| (.[0] | map(.field)),
(.[] | map( .value | gsub("\n"; "\n")))
| @csv
使用您的 JSON 并使用 -r 命令行选项调用它会产生:
"field1","field2"
"value1-1","value1-2\n"
"value2-1","value2-2\n"
我要转换存储在文件中的以下JSON内容tmp.json
{
"results": [
[
{
"field": "field1",
"value": "value1-1"
},
{
"field": "field2",
"value": "value1-2\n"
}
],
[
{
"field": "field1",
"value": "value2-1"
},
{
"field": "field2",
"value": "value2-2\n"
}
]
]
}
转换为 CSV 输出
"field1","field2"
"value1-1","value1-2\n"
"value2-1","value2-2\n"
然而,当我使用此 jq
命令时,
cat tmp.json | jq -r '.results | (first | map(.field)), (.[] | map(.value)) | @csv'
我得到这个结果:
"field1","field2"
"value1-1","value1-2
"
"value2-1","value2-2
"
应该如何编写 jq
命令以获得所需的 CSV 结果?
如果换行符是您唯一可以处理的,也许您可以进行字符串替换。
cat tmp.json | jq -r '.results | (first | map(.field)), (.[] | map(.value) | map(gsub("\n"; "\n"))) | @csv'
对于仅 jq 的解决方案,您可以使用 gsub("\n"; "\n")
。我会选择这样的东西:
.results
| (.[0] | map(.field)),
(.[] | map( .value | gsub("\n"; "\n")))
| @csv
使用您的 JSON 并使用 -r 命令行选项调用它会产生:
"field1","field2"
"value1-1","value1-2\n"
"value2-1","value2-2\n"