skip to Main Content

I have JSON data as below, in 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"}
}

I have a variable eg $PRID that contains prID value already.

I want to pass this to jq and fetch or get an output of IS_CR value for the respective prID.

I tried
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

but none worked as it gives null or nothing returns.

kindly help on this

2

Answers


  1. --arg creates a string variable, but your prId properties are numbers (6644 != "6644").

    Use --argjson instead:

    jq --argjson v "$PRID" '.[] | select(.prId == $v).IS_CR' services.json 
    
    Login or Signup to reply.
  2. Use:
    jq '.[] | select(.prId == '"$PRID"') | .IS_CR' services.json

    Output:

    # 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"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search