使用 jq 命令转换 json 输入

transform json input using jq command

我有以下 json 来自互联网服务的输入:

{
  "sunarme": "foo",
  "id": "foo-id",
  "name": "Foo bar",
  "profile": [
    {
      "id": "test1",
      "products": [
        "product1",
        "product2"
      ],
      "description": "test1 description"
     },
     {
      "id": "test2",
      "products": [
        "product3",
        "product4",
        "product5"
      ],
      "description": "test2 description"
     },
     {
      "id": "test3",
      "products": [
        "product6",
        "product7",
        "product8"
      ],
      "description": "test2 description"
      }
   ]
}

所以我需要将配置文件键从数组转换为 json 对象。这是所需的输出:

{
  "sunarme": "foo",
  "id": "foo-id",
  "name": "Foo bar",
  "profile": {
      "test1": [
        "product1",
        "product2"
      ],
      "test2": [
        "product3",
        "product4",
        "product5"
      ],
      "test3": [
        "product6",
        "product7",
        "product8"
      ]
   }
}

我不知道如何在 jq 命令中执行此操作,你能帮我吗?

提前致谢。

使用 with_entries,如果您相应地调整 .key,则可以将数组转换为对象。

jq '.profile |= with_entries(.key = .value.id | .value |= .products)'

Demo

或者使用reduce通过遍历数组来构建对象。

jq '.profile |= reduce .[] as $p ({}; .[$p.id] = $p.products)'

Demo

或使用map将每个数组项转换为一个对象,然后使用add合并它们。

jq '.profile |= (map({(.id): .products}) | add)'

Demo

输出为:

{
  "sunarme": "foo",
  "id": "foo-id",
  "name": "Foo bar",
  "profile": {
    "test1": [
      "product1",
      "product2"
    ],
    "test2": [
      "product3",
      "product4",
      "product5"
    ],
    "test3": [
      "product6",
      "product7",
      "product8"
    ]
  }
}