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

如何用Linux的jq命令提取JSON指定字段并转为CSV

使用jq将JSON转换为指定CSV(提取id和type字段)

假设你的JSON文件(比如data.json)结构如下,核心是包含results数组:

{
"results": [
{"id": "101", "type": "user", "other_field": "value"},
{"id": "102", "type": "admin", "other_field": "value"}
]
}

基础提取(无表头)

直接提取results数组中每个元素的id和type字段并转为CSV:

jq -r '.results[] | [.id, .type] | @csv' data.json

带表头的CSV输出

如果需要在CSV开头添加id,type表头行,用以下命令:

jq -r '["id", "type"], (.results[] | [.id, .type]) | @csv' data.json

命令各部分解释

  • -r:输出原始字符串(避免JSON格式的引号包裹)
  • .results[]:遍历results数组中的每一个元素
  • [.id, .type]:将当前元素的id和type字段组合成一个数组
  • @csv:把数组格式化为符合规范的CSV格式(自动处理特殊字符转义、引号包裹)

示例输出

运行带表头的命令后,输出结果如下:

"id","type"
"101","user"
"102","admin"

导出到文件

如果要将结果保存到CSV文件,使用重定向:

jq -r '["id", "type"], (.results[] | [.id, .type]) | @csv' data.json > output.csv

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:35:02