我有一个看起来像这样的JSON对象:
{
"a": [{
"last": "other",
"b": [{
"first": "John",
"last": "Doe"
}]
}, {
"last": "other",
"b": [{
"first": "Jane",
"last": "Doe"
}]
}, {
"last": "other",
"b": [{
"first": "John",
"last": "Smith"
}]
}]
}
我想使用 jq 根据"last"的值将其转换为单个对象数组。 所需的输出如下所示:
[{
"last": "Doe"
},
{
"last": "Smith"
}]
其中仅包含作为"b"子项的"last"的唯一值。 就我而言,我不关心任何其他领域。
以下是使用..
的原始问题的解决方案(即,使用"最后一个"键扫描对象,无论它们在哪里(:
[.. | select(.last?).last]
| unique
| map({last: .})
这可以很容易地修改以解决修改后的问题:
[.. | select( (.b?|type) == "array")
| .b[] | select(.last?).last ]
| unique
| map({last: .})
警告
unique
执行排序。 如果您希望遵守 .last 值的顺序,则可以使用以下帮助程序函数,前提是所有 .last 值都是字符串:
def uniques(stream):
foreach stream as $s ({};
if .[$s] then .emit = false else .emit = true | (.item = $s) | (.[$s]=true) end;
if .emit then .item else empty end );
| [ uniques(.. | select(.b?).b[] | select(.last?).last) | {last: .}]