如何使用 jq 使用子数组中的任意键创建 object?
How to use jq to create an object with an arbitrary key from a sub array?
请随意编辑标题,我不确定如何最好地表达它:)。
我有 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'
提取类别
但是我一直没能把它们组合起来。
感谢任何帮助
这实际上是相对简单的:
.things | .[] | {name: .name, category: .params | .[] | select(.key=="category") | .value }
您的 params
几乎看起来像 key/value 条目,因此您可以通过将数组传递给 from_entries
从它们创建一个对象。所以要组合所有东西,你只需要这样做:
.things | map({name} + (.params | from_entries))
这产生:
[
{
"name": "foo",
"key1": "val1",
"category": "thefoocategory"
},
{
"name": "bar",
"key1": "val1",
"category": "thebarcategory"
}
]
请随意编辑标题,我不确定如何最好地表达它:)。
我有 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'
但是我一直没能把它们组合起来。
感谢任何帮助
这实际上是相对简单的:
.things | .[] | {name: .name, category: .params | .[] | select(.key=="category") | .value }
您的 params
几乎看起来像 key/value 条目,因此您可以通过将数组传递给 from_entries
从它们创建一个对象。所以要组合所有东西,你只需要这样做:
.things | map({name} + (.params | from_entries))
这产生:
[
{
"name": "foo",
"key1": "val1",
"category": "thefoocategory"
},
{
"name": "bar",
"key1": "val1",
"category": "thebarcategory"
}
]