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



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

我的目标是替换HeaderAuthentication下的api-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
}

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

将您的过滤器表达式放在(..)中,这意味着它将从根应用于节点结构,而不仅仅是在.Headers[]中。一旦在parent下,使用更新赋值|=或普通赋值使其工作。

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

最新更新