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

如何使用JQ将多个筛选出的哈希合并为单个哈希?

解决jq合并多个独立对象为单个哈希的问题

你遇到的错误是因为使用map()时,输入流已经被.[]展开成了单个对象,后续map会遍历对象的字符串键,自然无法对字符串索引entity_id,因此报错。

以下两种方法可以实现你需要的合并效果:

方法1:用reduce逐步构建合并对象

直接遍历原数组,筛选符合条件的元素并逐步拼接目标对象:

reduce .[] as $item ({};
  if $item.entity_id | test("sensor.current.") then
    . + { ($item.entity_id): $item.state }
  else
    .
  end
)

方法2:先收集对象到数组,再用add合并

先把筛选后的单个对象存入数组,再通过add合并数组内的所有对象:

[.[] | select(.entity_id | test("sensor.current.")) | { (.entity_id): .state }] | add

执行上述任意命令后,都会得到你期望的单个哈希结构:

{
  "sensor.current_consumption": "1.4",
  "sensor.current_power": "194.6",
  "sensor.current_mains_voltage": "239.9"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:52:09