如何使用jq从子数组创建具有任意键的对象?

geo*_*off 4 json jq

请随意编辑标题,我不知道如何最好地表达它:).

我有JSON,例如,看起来像这样:

{
  "things": [
     {
        "name": "foo",
        "params": [
           {
             "type": "t1",
              "key": "key1",
              "value": "val1"
           },
           {
              "type": "t1",
              "key": "category",
              "value": "thefoocategory"
           }
        ]
      },
      {
        "name": "bar",
        "params": [
           {
             "type": "t1",
             "key": "key1",
             "value": "val1"
           },
           {
             "type": "t1",
             "key": "category",
             "value": "thebarcategory"
           }
        ]
     }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想要实现的是输出看起来像

[
  {
    name: "foo",
    category: "thefoocategory"
  },
  {
    name: "bar",
    category: "thebarcategory"
  }
]
Run Code Online (Sandbox Code Playgroud)

我能够很容易地提取名称 jq ' .things | .[] | .name'

我也可以提取类别 jq ' .things | .[] | .params | .[] | select(.key == "category") | .value'

但我无法将它们结合起来.

任何帮助赞赏

geo*_*off 10

这实际上相对简单:

.things | .[] | {name: .name, category: .params | .[] | select(.key=="category") | .value }
Run Code Online (Sandbox Code Playgroud)

  • 我认为您可以缩短`things | 。[]`到`things []` (2认同)