使用jq将字典列表合并到一个带有键的字典中

问题描述 投票:0回答:1

我有一本字典,比如:

{
    "Items": [
        {
            "ID": "123abc",
            "Name": "test name",
            "Description": "item 1"
        },
        {
            "ID": "321zyx",
            "Name": "test name two",
            "Description": "item 2"
        }
    ]
}

我想用

jq
将其转换为:

{
    "123abc": {
        "Name": "test name",
        "Description": "item 1"
    },
    "321zyx": {
        "Name": "test name two",
        "Description": "item 2"
    }
}

这可能吗?如果是这样,我将如何实现这一目标?

jq
1个回答
0
投票

使用

INDEX
function 接受流并创建对象,使用给定索引(本例中为
.ID
)作为键:

jq 'INDEX(.Items[]; .ID)' input.json
{
  "123abc": {
    "ID": "123abc",
    "Name": "test name",
    "Description": "item 1"
  },
  "321zyx": {
    "ID": "321zyx",
    "Name": "test name two",
    "Description": "item 2"
  }
}

演示

© www.soinside.com 2019 - 2024. All rights reserved.