Bash 如何使用jq根据唯一的键值组合来自同一个JSON对象的两个数组?
我有一个JSON对象,如下所示:Bash 如何使用jq根据唯一的键值组合来自同一个JSON对象的两个数组?,bash,jq,Bash,Jq,我有一个JSON对象,如下所示: { "a": [{ "last": "other", "b": [{ "first": "John", "last": "Doe" }] }, { "last": "other", "b": [{ "first": "Jane", "last": "Doe"
{
"a": [{
"last": "other",
"b": [{
"first": "John",
"last": "Doe"
}]
}, {
"last": "other",
"b": [{
"first": "Jane",
"last": "Doe"
}]
}, {
"last": "other",
"b": [{
"first": "John",
"last": "Smith"
}]
}]
}
[{
"last": "Doe"
},
{
"last": "Smith"
}]
我想使用jq将其转换为基于“last”值的单个对象数组。所需的输出如下:
{
"a": [{
"last": "other",
"b": [{
"first": "John",
"last": "Doe"
}]
}, {
"last": "other",
"b": [{
"first": "Jane",
"last": "Doe"
}]
}, {
"last": "other",
"b": [{
"first": "John",
"last": "Smith"
}]
}]
}
[{
"last": "Doe"
},
{
"last": "Smith"
}]
其中仅包括“b”的子项“last”的唯一值。就我而言,我不关心任何其他领域 这里有一个原始问题的解决方案,使用
。
(即,使用“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 );
你的回答对我的问题100%正确。然而,当我问这个问题时,我把我的例子简化了一点。实际数据看起来更像这样:{“a”:[{“last”:“other”,“b”:[{“first”:“John”,“last”:“Doe”}]},{“last”:“other”,“b”:[{“first”:“Jane”,“last”:“Doe”}]},{“last”:“other”,“b”:[{“first”:“John”,“last”:“Smith”}]}}我不想要与“b”对等的“last”。我在原始帖子中更新了示例,以更准确地反映数据。我试图修改您的答案以解决问题,但我猜仍然不理解此语法。感谢您的帮助。