2017-06-29 79 views
0

這是我的json。jq選擇在嵌套json bash中具有特定值的對象

[ 
{ 
    "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」。所以如果你有任何方法來選擇一個給定鍵名的對象,它也應該可以工作。

謝謝! :)

回答

0

濾波器:

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

產生首先提及的可容許的結果。如果你的jq沒有any/2那麼我會建議升級。如果這不是一種選擇,那麼你可以使用下面的簡單而低效的過濾器來代替:

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

或者:

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

它非常好!謝謝。 :) – Eleanor