json 通过匹配变量的父值之一,获得jq值[duplicate]

nkhmeac6  于 2023-02-10  发布在  其他
关注(0)|答案(2)|浏览(142)
    • 此问题在此处已有答案**:

How can I put integer as an argument in jq?(1个答案)
Numeric argument passed with jq --arg not matching data with ==(2个答案)
2天前关闭。
我在services.json中有如下JSON数据

{
"checkout-serviceA":{"prId":6644,"Sourcebranch":"","HFX":false,"IS_CR":"Yes"},
"checkout-serviceB":{"prId":15826,"Sourcebranch":"","HFX":false,"IS_CR": "no"},
"checkout-toggle":{"prId":8963,"Sourcebranch":"","HFX":true,"IS_CR": "Yes"},
"checkout-res":{"prId":1104,"Sourcebranch":"","HFX":false,"IS_CR": "Yes"}
}

我有一个变量,例如$PRID,它已经包含prID值。
我想把它传递给jq,然后为相应的prID获取IS_CR值的输出。
我试过jq --arg v "$PRID" '.[] | select(.prId == $v).IS_CR' services.json
&
jq --arg v "$PRID" 'to_entries | map(select(.value.prId == $v))[0].value.IS_CR' services.json
但是没有一个工作,因为它给出null或nothing返回。
请帮忙

dluptydi

dluptydi1#

--arg创建一个字符串变量,但prId属性是数字(6644 != "6644")。
请改用--argjson

jq --argjson v "$PRID" '.[] | select(.prId == $v).IS_CR' services.json
bjp0bcyl

bjp0bcyl2#

使用:jq '.[] | select(.prId == '"$PRID"') | .IS_CR' services.json
输出:

# PRID=6644
# cat services.json
{
"checkout-serviceA":{"prId":6644,"Sourcebranch":"","HFX":false,"IS_CR":"Yes"},
"checkout-serviceB":{"prId":15826,"Sourcebranch":"","HFX":false,"IS_CR": "no"},
"checkout-toggle":{"prId":8963,"Sourcebranch":"","HFX":true,"IS_CR": "Yes"},
"checkout-res":{"prId":1104,"Sourcebranch":"","HFX":false,"IS_CR": "Yes"}
}
# jq '.[] | select(.prId == '"$PRID"') | .IS_CR' services.json
"Yes"

相关问题