如何用JQ从嵌套Map中提取并合并实例数据?
JQ合并多实例Map为单一Map
原始JSON数据
{ "version": 2, "clients": { "c1": { "updated": "0001-01-01T00:00:00Z", "instances": { "i1": { "updated": "2023-03-19T17:45:03.703984279+01:00", "chargePower": 349.9999940395355 } } }, "c2": { "updated": "0001-01-01T00:00:00Z", "instances": { "i2": { "updated": "2023-02-10T18:34:56.352428175+01:00", "chargePower": 0 } } } } }
期望输出
{ "i1": { "updated": "2023-03-19T17:45:03.703984279+01:00", "chargePower": 349.9999940395355 }, "i2": { "updated": "2023-02-10T18:34:56.352428175+01:00", "chargePower": 0 } }
当前问题
使用命令:
.clients | to_entries | .[].value.instances
执行后得到两个独立对象,无法合并为单一Map:
{ "i1": { "updated": "2023-03-19T17:45:03.703984279+01:00", "chargePower": 349.9999940395355 } } { "i2": { "updated": "2023-02-10T18:34:56.352428175+01:00", "chargePower": 0 } }
解决方案
使用以下JQ命令即可合并为单一Map:
.clients | map(.instances) | add
命令解释
map(.instances):遍历clients下的所有客户端对象,提取每个客户端的instances对象并收集到数组中。add:将数组中的多个对象合并为一个单一对象,若存在键名冲突,后续对象会覆盖前置对象(示例无冲突场景)。
也可使用更简洁的写法:
.clients[].instances | add
内容的提问来源于stack exchange,提问作者andig
相关产品推荐
相关产品推荐

