Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jq to suffix a string to a field in an object not containing it

Tags:

jq

I have a json as follows:

{
  "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "batchPools": {
      "value": [
        {
          "networkConfiguration": {
            "subnetId": "/subscriptions/xxxx/resourceGroups/xxx/providers/Microsoft.Network/virtualNetworks/xxxxx/subnets/sample-name-batch",
            "subnetAddressPrefix": ""
          }
        },
        {
          "networkConfiguration": {
            "subnetId": "/subscriptions/xxxx/resourceGroups/xxx/providers/Microsoft.Network/virtualNetworks/xxxxx/subnets/sample-name",
            "subnetAddressPrefix": ""
          }
        }
      ]
    }
  }
}

I need to check if any of the networkConfiguration.subnetID under the array value contains the string batch. If yes then nothing needs to be done. Else, append -batch to the existing value. In this case, only the second networkConfiguration.subnetID of the array should be updated.

I tried the following:

(.parameters.batchPools.value[] | select(.networkConfiguration.subnetId | contains("-batch") | not) | .networkConfiguration.subnetId) |= (.networkConfiguration.subnetId+"-batch")

I get the following error: jq: error (at <stdin>:38): Cannot index string with string "networkConfiguration" exit status 5

I tried this:

(.parameters.batchPools.value[] | select(.networkConfiguration.subnetId | contains("batch") | not) | .networkConfiguration.subnetId) |= "someValue"

This worked fine and replaced the entire subnetId with someValue. I am not able to figure out why the previous command is not working out. Please help.

like image 464
Abhra Ray Avatar asked Dec 13 '25 14:12

Abhra Ray


1 Answers

You don't need to use the whole path of subnetId again. You've already selected that node from the pipeline before. Just use the += append operator to suffix the required string

( .parameters.batchPools.value[] | 
  select(.networkConfiguration.subnetId | contains("batch") | not) | 
  .networkConfiguration.subnetId ) += "-batch"

jqplay - Online demo

like image 149
Inian Avatar answered Dec 16 '25 20:12

Inian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!