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

使用jq提取JSON指定字段转换为CSV的语法问题求助

错误原因

你原来的命令存在3个问题:

  • 输入的file.json是单个JSON对象,不是对象数组,不需要调用map()遍历
  • jq构造对象时不能直接用discovered_data.mac_address这种带点的格式作为键名,需要手动指定键名、同时关联对应嵌套层级的取值
  • names字段是数组类型,需要取第一个元素才能得到纯字符串值,否则输出会带有数组括号
修正后命令

如果你的输入始终是单个JSON对象,使用以下命令即可得到你期望的输出:

jq -r '["names","ip_address","discovered_data.mac_address","discovered_data.discovered_name"], [.names[0], .ip_address, .discovered_data.mac_address, .discovered_data.discovered_name] | join(",")' file.json

如果需要生成带引号的标准CSV格式(兼容带逗号、特殊字符的字段值),将末尾的join(",")替换为@csv即可。

如果你的实际场景输入是多个JSON对象组成的数组,使用以下适配版本:

jq -r '["names","ip_address","discovered_data.mac_address","discovered_data.discovered_name"], (.[] | [.names[0], .ip_address, .discovered_data.mac_address, .discovered_data.discovered_name]) | join(",")' file.json

内容的提问来源于stack exchange,提问作者K2-Beast

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:15:03