You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JQ将数组流转换为CSV?解决转换报错问题

问题:将JQ输出的数组流转换为CSV时出错

我通过JQ过滤JSON文件得到了一组数组流数据,想转成CSV文件,执行命令cat file.json | jq '.[]| join(",")'时弹出错误:jq: error (at <stdin>:8): Cannot iterate over string ("https://lo...)。

输入的数组流内容:

[
  "https://localhost/rundeck/project/Enterprise/execution/show/228",
  "succeeded",
  "Enterprise",
  "2020-04-19T03:00:01Z",
  "2020-04-19T03:13:17Z",
  "job_particion"
]
[
  "https://localhost/rundeck/project/Enterprise/execution/show/824",
  "succeeded",
  "Enterprise",
  "2020-09-01T04:15:00Z",
  "2020-09-01T04:15:02Z",
  "job_scheduler"
]
[
  "https://localhost/rundeck/project/Enterprise/execution/show/822",
  "succeeded",
  "Enterprise",
  "2020-09-01T03:45:00Z",
  "2020-09-01T03:45:06Z",
  "job_system"
]
[
  "https://localhost/rundeck/project/Enterprise/execution/show/823",
  "succeeded",
  "Enterprise",
  "2020-09-01T04:00:00Z",
  "2020-09-01T04:00:25Z",
  "job_operator"
]
[
  "https://localhost/rundeck/project/Enterprise/execution/show/821",
  "succeeded",
  "Enterprise",
  "2020-09-01T03:30:00Z",
  "2020-09-01T03:30:10Z",
  "job_aplication"
]

错误原因

你的命令逻辑有误:.[]会把数组内的每个元素(比如URL字符串)单独提取出来,然后尝试对字符串执行join(",")——但join是数组专属方法,字符串无法调用该方法,因此触发“不能遍历字符串”的错误。

解决方案

需要直接对每个完整数组调用join(","),无需遍历数组内元素:

基础转换命令

cat file.json | jq 'join(",")'

标准CSV转换(推荐)

如果要生成符合规范的CSV(自动处理含逗号的字段),使用jq内置的@csv过滤器,它会自动给需要的字段添加引号:

cat file.json | jq '@csv'

执行后输出的标准CSV内容:

"https://localhost/rundeck/project/Enterprise/execution/show/228","succeeded","Enterprise","2020-04-19T03:00:01Z","2020-04-19T03:13:17Z","job_particion"
"https://localhost/rundeck/project/Enterprise/execution/show/824","succeeded","Enterprise","2020-09-01T04:15:00Z","2020-09-01T04:15:02Z","job_scheduler"
"https://localhost/rundeck/project/Enterprise/execution/show/822","succeeded","Enterprise","2020-09-01T03:45:00Z","2020-09-01T03:45:06Z","job_system"
"https://localhost/rundeck/project/Enterprise/execution/show/823","succeeded","Enterprise","2020-09-01T04:00:00Z","2020-09-01T04:00:25Z","job_operator"
"https://localhost/rundeck/project/Enterprise/execution/show/821","succeeded","Enterprise","2020-09-01T03:30:00Z","2020-09-01T03:30:10Z","job_aplication"

内容的提问来源于stack exchange,提问作者anywhere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 21:10:47