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

如何用jq提取JSON父字段及嵌套子数组字段值?

调整jq命令实现同时提取parent与子数组字段

当curl返回的JSON结构如下时:

{
  "parent": "John Smith",
  "dob": "August 6, 2020",
  "children": [
    {
      "first": "Bob",
      "last": "Smith"
    },
    {
      "first": "John",
      "last": "Smith"
    }
  ]
}

你需要提取parent字段,以及children数组中每个子项的first、last字段。注意你原命令里的.childrens是拼写错误,正确的键名是.children。

正确命令

curl -G 'http://someapi' | jq '.parent, .children[] | .first, .last'

输出结果

John Smith
Bob
Smith
John
Smith

命令解释

  • .parent:直接输出根节点的parent字段值
  • .children[]:遍历children数组的每一个元素
  • .first, .last:对每个数组元素,依次输出first和last字段值

如果需要更明确的优先级(避免数组为空时可能出现的异常),也可以给数组遍历部分加上括号:

curl -G 'http://someapi' | jq '.parent, (.children[] | .first, .last)'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:07:11