Mar*_*rty 5 unix bash shell json jq
想知道在查询子“Id”时是否可以从下面的 json 返回父“Id”
{
"DistributionList": {
"Items": [
{
"Origins": {
"Items": [
{
"Id": "abc"
}
],
"Quantity": 1
},
"Id": "parent123"
},
{
"Origins": {
"Items": [
{
"Id": "def"
}
],
"Quantity": 1
},
"Id": "parent345"
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
例如。如果我查询子 ID“abc”,它应该返回“parent123”。
做类似的事情:
more jsonfile | jq '.DistributionList.Items[].Origins.Items[] | select(.Id == "abc") | .Id'
Run Code Online (Sandbox Code Playgroud)
只会返回“abc”->但我需要父ID。不确定是否有办法用 jq 做到这一点
过滤器:
.. | objects | select(.Origins.Items[]? | .Id == "abc") | .Id
Run Code Online (Sandbox Code Playgroud)
产生:
"parent123"
Run Code Online (Sandbox Code Playgroud)
您可能想要参数化过滤器,例如:
def parent(child):
.. | objects | select( .Origins.Items[]? | .Id == child) | .Id ;
Run Code Online (Sandbox Code Playgroud)