如何在 jq 脚本文件的命令中使用环境变量?

Tim*_*uck 5 json ksh jq

我正在处理大量 OpenAPI 3.0.0 文件,我需要从中创建 html 页面。每个 OpenAPI 文件代表大对象模型中的一个实体。Swagger Viewer、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": "..."
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的解决方案中,我使用 jq 来解析文件(macOS、ksh)。由于有这么多,我想将一个环境变量传递给jq。这在 shell 中很简单:

 % entity_name=my_entity_name
 % jq -r 'select(.components.schemas.'$entity_name'.properties != null)' file.json
Run Code Online (Sandbox Code Playgroud)

在脚本文件中,方法是类似的,我得到了我期望的结果。但是,考虑到我想要做的事情的性质,我想使用 jq -f 选项将 jq 命令放入文件中。

我尝试将以下内容放入名为的文件中jqscript.jq

 select(.components.schemas.'$entity_name'.properties != null)
Run Code Online (Sandbox Code Playgroud)

我这样打电话:

  % jq -rf jqscript.jq --arg entity_name "$entity_name" file.json
Run Code Online (Sandbox Code Playgroud)

这会导致错误:

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
Run Code Online (Sandbox Code Playgroud)

我试图通过修改'$entity_name'to $entity_name(删除单引号)、$[entity_name]${entity_name}等来破译如何在这种情况下使用环境变量,但我得到了类似的结果。

我能够使用以下示例脚本验证变量是否可以传递到 jq 脚本文件:

value: $entity_name
} |
.value
Run Code Online (Sandbox Code Playgroud)

当我使用此文件运行时% jq -rf jqscript.jq --arg entity_name "$entity_name" file.json,我得到了返回的entity_name 的预期值。

如何使用 jq 命令中和 jq 脚本文件中的环境变量?

che*_*ner 3

您正在使用变量的动态构建过滤器。这是脆弱的,因为解析结果表达式,而不是直接使用变量的值(类似于 SQL 注入攻击)。

您可以直接使用 访问环境$ENV

 % export entity_name=my_entity_name
 % jq -r 'select(.components.schemas[$ENV.entity_name].properties != null)' file.json
Run Code Online (Sandbox Code Playgroud)

或者只是将密钥作为显式参数传递

% jq -r --arg entity_name my_entity_name 'select(.components.schemas[$entity_name].properties != null)' file.json
Run Code Online (Sandbox Code Playgroud)