gpt4 book ai didi

json - jq 选择在嵌套 json bash 中具有特定值的对象

转载 作者:行者123 更新时间:2023-12-01 21:31:30 25 4
gpt4 key购买 nike

这是我的 json。

[
{
"time": "2017-06-10 00:00:48-0400,317",
"UserInfo": {
"AppId": "ONE_SEARCH",
"UsageGroupId": "92600",
},
"Items": [
{
"PublicationCode": "",
"OpenUrlRefId": "",
"ReferringUrl": "N",
"OpenAccess": "0",
"ItmId": "1328515516"
}
]
},
{
"time": "2017-06-10 00:00:48-0400,548",
"UserInfo": {
"AppId": "DIALOG",
"UsageGroupId": "1195735",
},
"Items": [
{
"Origin": "Alert",
"PublicationCode": "",
"NumberOfCopies": 1,
"ItmId": "1907446549"
},
{
"Origin": "Alert",
"PublicationCode": "",
"NumberOfCopies": 1,
"ItmId": "1907446950",
}
]
}
]

我想使用 jq 提取其元素“Items”中具有“Origin”:“Alert”的对象。结果应该如下所示:

{
"time": "2017-06-10 00:00:48-0400,548",
"UserInfo": {
"AppId": "DIALOG",
"UsageGroupId": "1195735",
},
"Items": [
{
"Origin": "Alert",
"PublicationCode": "",
"NumberOfCopies": 1,
"ItmId": "1907446549"
},
{
"Origin": "Alert",
"PublicationCode": "",
"NumberOfCopies": 1,
"ItmId": "1907446950",
}
]
}

或者这个:

{
"Items": [
{
"Origin": "Alert",
"PublicationCode": "",
"NumberOfCopies": 1,
"ItmId": "1907446549",
"ReasonCode": ""
},
{
"Origin": "Alert",
"PublicationCode": "",
"NumberOfCopies": 1,
"ItmId": "1907446950",
}
]
}

如何使用jq来做到这一点?我尝试了多种方法,但大多数方法只会返回一个包含所有子对象的数组,其中包含“Origin”:“Alert”。我需要这些子对象仍然保持结构,因为我需要知道它们中的哪些一起发生,哪些单独发生。

顺便说一句,“Origin”的唯一值是“Alert”。因此,如果您有任何方法来选择具有给定键名称的对象,它也应该有效。

谢谢! :)

最佳答案

过滤器:

.[] | select( any(.Items[]; .Origin == "Alert"))

产生第一个提到的可接受的结果。如果您的 jq 没有 any/2 那么我建议升级。如果这不是一个选项,那么您可以使用以下简单但效率较低的过滤器:

.[] | select( .Items | map(.Origin) | index("Alert"))

或者:

.[] | select(reduce .Items[] as $item (false; . or ($item | .Origin == "Alert")))

关于json - jq 选择在嵌套 json bash 中具有特定值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44832475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com