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

时间:2016-06-16 16:24:58

标签: 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"
           }
        ]
     }
  ]
}

我想要实现的是看起来像

的输出
[
  {
    name: "foo",
    category: "thefoocategory"
  },
  {
    name: "bar",
    category: "thebarcategory"
  }
]

我可以使用jq ' .things | .[] | .name'

轻松提取名称

我还可以使用jq ' .things | .[] | .params | .[] | select(.key == "category") | .value'

提取类别

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

任何帮助表示赞赏

2 个答案:

答案 0 :(得分:8)

这实际上相对简单:

.things | .[] | {name: .name, category: .params | .[] | select(.key=="category") | .value }

答案 1 :(得分:1)

您的params几乎看起来像键/值条目,因此您可以通过将数组传递给from_entries来创建一个对象。所以要结合一切,你只需要这样做:

.things | map({name} + (.params | from_entries))

这会产生:

[
  {
    "name": "foo",
    "key1": "val1",
    "category": "thefoocategory"
  },
  {
    "name": "bar",
    "key1": "val1",
    "category": "thebarcategory"
  }
]