我正在处理大量的 OpenAPI 3.0.0 文件,我需要从中创建 html 页面。每个 OpenAPI 文件都代表大对象模型中的一个实体。Swagger 查看器、redoc-cli 和其他工具无法生成我需要的文档类型。这是一个示例文件:
{
"openapi": "3.0.0",
"paths": {},
"info": {
"title": "My File",
"version": "1.0.0"
},
"components": {
"schemas": {
"my_entity_name": {
"type": "object",
"description": "....",
"properties": {
"propertyOne": {
"type": "string",
"description": "..."
},
"propertyTwo": {
"type": "string",
"format": "date",
"description": "..."
}
}
}
}
}
}
在我的解决方案中,我使用 jq 来解析文件(macOS、ksh)。由于有这么多,我想将一个环境变量传递给jq。这在 shell 中很简单:
% entity_name=my_entity_name
% jq -r 'select(.components.schemas.'$entity_name'.properties != null)' file.json
在脚本文件中,方法类似,我得到了我期望的结果。但是,鉴于我正在尝试做的事情的性质,我想使用 jq -f 选项将 jq 命令放入文件中。
我尝试将以下内容放入名为的文件中jqscript.jq
:
select(.components.schemas.'$entity_name'.properties != null)
我这样打电话:
% jq -rf jqscript.jq --arg entity_name "$entity_name" file.json
这会导致错误:
jq: error: syntax error, unexpected INVALID_CHARACTER, expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
select(.components.schemas.'$entity_name'.properties != null)
jq: 1 compile error
我试图通过修改'$entity_name'
to $entity_name
(删除单引号)、$[entity_name]
、${entity_name}
等来破译如何在这种情况下使用环境变量,但我得到了类似的结果。
我能够使用以下示例脚本验证变量是否可以传递给 jq 脚本文件:
value: $entity_name
} |
.value
当我使用这个文件运行时% jq -rf jqscript.jq --arg entity_name "$entity_name" file.json
,我得到了 entity_name 返回的预期值。
如何使用既在 jq 命令中又在 jq 脚本文件中的环境变量?
您正在使用变量的值动态构建过滤器。这是脆弱的,因为结果表达式被解析,而不是按字面意思使用变量的值(类似于 SQL 注入攻击)。
您可以使用 直接访问环境$ENV
。
% export entity_name=my_entity_name
% jq -r 'select(.components.schemas[$ENV.entity_name].properties != null)' file.json
或者只是将密钥作为显式参数传递
% jq -r --arg entity_name my_entity_name 'select(.components.schemas[$entity_name].properties != null)' file.json
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句