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

使用jq解析嵌套对象内数组时输出出现对象重复问题

问题与解决方案

原始数据

{
  "Country": "India",
  "States": [
    {
      "Name": "TN",
      "Cities": [
        "city1",
        "city2"
      ]
    },
    {
      "Name": "KL",
      "Cities": [
        "city3",
        "city4"
      ]
    }
  ]
}

原使用的jq表达式

{
  country:.Country,states: .States | (
    foreach .[] as $item (0; 
      {
       name:$item.Name,
       city:$item.Cities
      } 
    )
  )
}

原输出结果

{
  "country": "India",
  "states": {
    "name": "TN",
    "city": [
      "city1",
      "city2"
    ]
  }
}
{
  "country": "India",
  "states": {
    "name": "KL",
    "city": [
      "city3",
      "city4"
    ]
  }
}

需求

  • 不要让country字段重复出现
  • 将原数据中的Cities键名修改为city

解决方案

使用以下jq表达式:

{
  country: .Country,
  states: .States | map({name: .Name, city: .Cities})
}

最终输出

{
  "country": "India",
  "states": [
    {
      "name": "TN",
      "city": [
        "city1",
        "city2"
      ]
    },
    {
      "name": "KL",
      "city": [
        "city3",
        "city4"
      ]
    }
  ]
}

说明

  • 直接保留顶层的country字段,确保它只出现一次
  • 用map()遍历States数组,对每个元素做键名映射:把Name转为name,Cities转为city,最后将处理后的数组赋值给states字段,同时满足两个需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 16:57:05