在Bash脚本中使用JQ动态添加JSON对象时的路径斜杠问题
解决Bash脚本中JQ生成JSON路径双反斜杠问题
问题场景
在Bash脚本中循环调用JQ动态构建JSON文件时,生成的JSON里file字段路径出现双反斜杠(\\),但需求是显示单反斜杠(\)。
初始脚本
touch credScanSuppressionsFile.json echo '{"tool": "Credential Scanner", "suppressions":[]}' | jq > credScanSuppressionsFile.json webapp_name=customer-brasil-forms for env in develop #staging demo preprod prod do file='azure_portal_variables\'$env-$webapp_name.json echo $file jq --arg file $file '.suppressions += [{"file": $file, "_justification": "app setting file"}]' <<< "$(cat credScanSuppressionsFile.json)" > credScanSuppressionsFile.json done
当前输出
{ "tool": "Credential Scanner", "suppressions": [ { "file": "azure_portal_variables\\develop-customer-brasil-forms.json", "_justification": "app setting file" } ] }
期望输出
{ "tool": "Credential Scanner", "suppressions": [ { "file": "azure_portal_variables\develop-customer-brasil-forms.json", "_justification": "app setting file" } ] }
关键说明
首先要明确:JSON规范中字符串内的反斜杠必须转义为双反斜杠,你期望的输出其实不符合JSON语法,会导致后续解析工具报错。如果是为了表示Windows路径,双反斜杠才是合法的标准写法——当用JSON解析工具读取该字段时,得到的实际值就是单个反斜杠的路径。
如果确实需要输出单反斜杠(比如特定工具的非标准要求),或者想改用跨平台兼容的路径格式,可参考以下解决方案:
解决方案
方案1:改用正斜杠(推荐,跨平台兼容)
将路径分隔符改为正斜杠,这样JSON中不会出现转义问题,且大多数系统和工具都能识别:
touch credScanSuppressionsFile.json echo '{"tool": "Credential Scanner", "suppressions":[]}' | jq > credScanSuppressionsFile.json webapp_name=customer-brasil-forms for env in develop #staging demo preprod prod do # 用正斜杠拼接路径 file="azure_portal_variables/$env-$webapp_name.json" echo $file # 用临时文件避免读写冲突 jq --arg file "$file" '.suppressions += [{"file": $file, "_justification": "app setting file"}]' credScanSuppressionsFile.json > temp.json && mv temp.json credScanSuppressionsFile.json done
生成的合法JSON输出:
{ "tool": "Credential Scanner", "suppressions": [ { "file": "azure_portal_variables/develop-customer-brasil-forms.json", "_justification": "app setting file" } ] }
方案2:生成非标准的单反斜杠JSON(不推荐)
如果必须输出单反斜杠,可直接在JQ中构造字符串,绕过变量转义逻辑,但生成的JSON不符合规范:
touch credScanSuppressionsFile.json echo '{"tool": "Credential Scanner", "suppressions":[]}' | jq > credScanSuppressionsFile.json webapp_name=customer-brasil-forms for env in develop #staging demo preprod prod do echo "azure_portal_variables\\$env-$webapp_name.json" # 直接在JQ中拼接字符串,不通过--arg传递 jq '.suppressions += [{"file": "azure_portal_variables\'"$env-$webapp_name"'.json", "_justification": "app setting file"}]' credScanSuppressionsFile.json > temp.json && mv temp.json credScanSuppressionsFile.json done
方案3:保留双反斜杠(合法标准)
如果你的解析工具支持标准JSON,无需修改——双反斜杠是JSON中表示单个反斜杠的正确方式,解析后得到的路径就是你需要的azure_portal_variables\develop-customer-brasil-forms.json。
内容的提问来源于stack exchange,提问作者Pablo García Garrido
相关产品推荐
相关产品推荐

