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

如何使用Jq命令将ticketId和requester_id合并到数组对象中?

正确的Jq解决方案:将ticketData属性批量添加到数组对象中

问题分析

你之前的命令返回null,原因是在map函数内部,当前上下文.指向的是componentsByProdTourId数组里的单个对象,这些对象本身没有ticketData属性,自然无法读取到对应值。需要先把外层的ticketData保存为变量,再在遍历数组时引用这个变量。

另外,期望输出中ticketId和requester_id是数字类型,而输入里是字符串,需要用tonumber做类型转换。

正确的Jq命令

.ticketData as $ticket | .componentsByProdTourId |= map(. + {ticketId: ($ticket.ticketId | tonumber), requester_id: ($ticket.requester_id | tonumber)})

命令说明

  • .ticketData as $ticket:将根节点下的ticketData对象存入变量$ticket,确保后续遍历数组时能访问到目标属性
  • .componentsByProdTourId |= map(...):对componentsByProdTourId数组进行修改,遍历每个对象并合并新属性
  • tonumber:把字符串类型的ID转换为数字,与期望输出的格式完全匹配

验证结果

执行上述命令后,输入JSON会被转换为你期望的输出:

{"componentsByProdTourId":[{"region":"Europe","compSpec":{"country":"France","attributes":[{"attributeCode":"ABC","attributeType":"xyx"}]},"ticketId":1234,"requester_id":99885},{"region":"Europe","compSpec":{"country":"France","attributes":[{"attributeCode":"EFG","attributeType":"lmn"}]},"ticketId":1234,"requester_id":99885},{"region":"Europe","compSpec":{"country":"United Kingdom","attributes":[{"attributeCode":"FLC","attributeType":"omp"}]},"ticketId":1234,"requester_id":99885}],"ticketData":{"ticketId":"1234","requester_id":"99885"}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:05:18