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

使用jq解析嵌套JSON数据:实现目标结构转换的技术问询

正确转换嵌套JSON的jq命令

原始JSON数据

[
 {
  "class": "class1",
  "year": "year1",
  "subject": [
   {
    "id": 7654,
    "type": "subject",
    "module": {
     "id": 765,
     "number": 654,
     "name": "maths",
     "unit": "vect"
    },
    "amount": 5.88
   },
   {
    "id": 7612,
    "type": "subject",
    "module": {
     "id": 747,
     "number": 234,
     "name": "electronics",
     "unit": "laws"
    },
    "amount": 2.3
   }
  ]
 },
 {
  "class": "class1",
  "year": "year2",
  "subject": [
   {
    "id": 8634,
    "type": "subject",
    "module": {
     "id": 465,
     "number": 253,
     "name": "electronics",
     "unit": "laws"
    },
    "amount": 12.51
   },
   {
    "id": 7654,
    "type": "subject",
    "module": {
     "id": 765,
     "number": 654,
     "name": "maths",
     "unit": "vect"
    },
    "amount": 4.44
   }
  ]
 }
]

目标转换结构

[
 {
  "year": "year1",
   "subject": [
    {
     "name": "maths",
     "unit": "vect",
     "amount": 5.88
    },
    {
     "name": "electronics",
     "unit": "laws",
     "amount": 2.3
    }
   ]
 },
 {
  "year": "year2",
   "subject": [
    {
     "name": "electronics",
     "unit": "laws",
     "amount": 12.51
    },
    {
     "name": "maths",
     "unit": "vect",
     "amount": 4.44
    }
   ]
 }
]

错误命令问题分析

你之前使用的命令:

jq '.[] | .year as $year | .subject[] | {$year, "name": .subject.name, "amount": .amount, "unit": .subject.unit}' < classes > test

存在两个核心问题:

  1. 遍历.subject[]后将每个subject单独输出为带year的对象,破坏了每个year对应一组subject的数组结构
  2. 错误引用字段:当前上下文已是subject对象,应取.module.name而非.subject.name

正确的jq命令

jq '[.[] | {year: .year, subject: .subject | map({name: .module.name, unit: .module.unit, amount: .amount})}]' < classes > test

命令逻辑说明

  • .[ ]:遍历原始数组中的每个class-year条目
  • {year: .year, ...}:保留year字段,同时重新构建subject数组
  • .subject | map(...):对每个subject数组内的元素做转换,提取module.name、module.unit和amount字段组成新对象
  • 最外层[ ... ]:将处理后的所有条目重新包裹为数组,保证输出符合目标JSON结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 04:23:11