【问题标题】:How to replace a value in json file using jq and returning the whole content如何使用 jq 替换 json 文件中的值并返回整个内容
【发布时间】:2021-08-18 20:39:38
【问题描述】:

我有一个这样的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
  }
}

我的目标是替换 HeaderAuthenticationapi-key 的值(它可以在任何索引中, 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。我看到一些使用海绵的stackoverflow帖子,我不能在我们的环境中使用海绵

【问题讨论】:

    标签: json linux jq


    【解决方案1】:

    将您的过滤器表达式放在(..) 中,这意味着它从根应用到节点结构,而不是单独在.Headers[] 中。一旦在括号下,使用更新分配|= 或正常分配使其工作。

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

    【讨论】:

      猜你喜欢
      • 2023-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多