代码之家  ›  专栏  ›  技术社区  ›  Reza

如何使用jq替换json文件中的值并返回整个内容

  •  0
  • Reza  · 技术社区  · 3 年前

    我有一个这样的json

    {
      "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
      }
    }
    

    我的目标是取代的价值 api-key 在下面 HeaderAuthentication (它可以在任何索引中,0、2、1…)

    我做到了

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

    问题似乎是 jq 只返回被替换的部分,但我需要整个文件,我做错了什么?

    这是运行命令后文件的内容

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

    ps。我看到一些堆叠的帖子使用海绵,我不能在我们的环境中使用海绵

    0 回复  |  直到 3 年前
        1
  •  2
  •   Inian    3 年前

    把你的过滤器表达式放在里面 (..) ,意味着它从根应用到节点结构,而不是在 .Headers[] 单独地在parens下之后,使用更新分配 |= 或者让它发挥作用的正常任务。

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