Json
如何使用 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 } }
我的目標是替換
api-key
under的值HeaderAuthentication
(它可以是索引 0 或 1 或 2 或任何)我做了這個
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 }
附言。我看到一些使用海綿的stackoverflow文章,我不能在我們的環境中使用海綿
jq
表達式_.HeaderAuthentication.Headers[] | select(.Name == "api-key")
挑選出作為其值的
Headers
數組元素。api-key``Name
表達方式
(.HeaderAuthentication.Headers[] | select(.Name == "api-key")).Value |= "NEW VALUE"
Value
將該數組元素中的鍵的值更新為文字字元串NEW VALUE
。從命令行使用包含新值的 shell 變數:
new_api_key='My new key' jq --arg newkey "$new_api_key" '(.HeaderAuthentication.Headers[] | select(.Name == "api-key")).Value |= $newkey' file.json
如果需要對密鑰進行 base64 編碼,請使用值
($newkey|@base64)
進行更新,而不是僅$newkey
在jq
表達式中進行更新。要就地進行更改,請使用類似
tmpfile=$(mktemp) cp file.json "$tmpfile" && jq --arg ...as above... "$tmpfile" >file.json && rm -f -- "$tmpfile"
或者,如果您不需要保留原始文件的權限和所有權等,
tmpfile=$(mktemp) jq --arg ...as above... file.json >"$tmpfile" && mv -- "$tmpfile" file.json