How to replace a value in json file using jq and returning the whole content

Viewed 1036

I have a json like this

{
  "AgentGroupId": null,
  "AgentId": null,
  "CreateType": "Website",
  "IsPrimary": true,
  "IsShared": true,
  "HeaderAuthentication": {
    "Headers": [
      {
        "Name": "api-key",
        "Value": "TEST_API_KEY_VALUE-2",
        "OriginalName": null,
        "IsReplacedCredentials": false
      },
      {
        "Name": "Authorization",
        "Value": "",
        "OriginalName": null,
        "IsReplacedCredentials": false
      }
    ],
    "IsEnabled": true
  },
  "IsTimeWindowEnabled": false,
  "AdditionalWebsites": [],
  "BasicAuthenticationApiModel": {
    "Credentials": null,
    "IsEnabled": false,
    "NoChallenge": false
  },
  "ClientCertificateAuthenticationSetting": null,
  "Cookies": null,
  "CrawlAndAttack": true,
  "EnableHeuristicChecksInCustomUrlRewrite": true,
  "ExcludedLinks": [
    {
      "RegexPattern": "gtm\\.js"
    },
    {
      "RegexPattern": "WebResource\\.axd"
    },
    {
      "RegexPattern": "ScriptResource\\.axd"
    }
  ],
  "ExcludedUsageTrackers": [],
  "DisallowedHttpMethods": [],
  "ExcludeLinks": true,
  "ExcludeAuthenticationPages": false,
  "FindAndFollowNewLinks": true,
  "FormAuthenticationSettingModel": {
    "Integrations": {},
    "CustomScripts": [],
    "InteractiveLoginRequired": false,
    "DefaultPersonaValidation": null,
    "DetectBearerToken": true,
    "DisableLogoutDetection": false,
    "IsEnabled": false,
    "LoginFormUrl": null,
    "LoginRequiredUrl": null,
    "LogoutKeywordPatterns": null,
    "LogoutKeywordPatternsValue": null,
    "LogoutRedirectPattern": null,
    "OverrideTargetUrl": false,
    "Personas": [],
    "PersonasValidation": null
  }
}

My goal is to replace the value of api-key under HeaderAuthentication (it could be in any index , 0 , 2, 1, ...)

I did this

jq '.HeaderAuthentication.Headers[] | select(.Name == "api-key") | .Value = "xxx"' scanprofile.json > tmp && mv tmp scanprofile.json

The issue is seems jq is returning only the part that replaced, but I need the whole file, what I am doing wrong?

this is the content of file after running the command

{
  "Name": "api-key",
  "Value": "xxx",
  "OriginalName": null,
  "IsReplacedCredentials": false
}

ps. I saw some stackoverflow post using sponge, I can't use sponge in our environment

1 Answers

Put your filter expression inside (..), meaning it to apply to the node structure from root, and not within .Headers[] alone. Once under parens, use the update assignment |= or the normal assignment to make it work.

( .HeaderAuthentication.Headers[] | select(.Name == "api-key") | .Value ) |= "xxx"
Related