linux - jq select 动态项,其中 key 是环境变量而不是 bash 变量

标签 linux bash jq

我有以下 json:

{
    "feature/EBS_DDS_SC-27428": {
        "auth": "http://test123:8080/service.jsp",
        "publish": "http://test234:8080/service.jsp",
        "general_name": "PG"
    },
    "feature/EBS_DDS_SC-27428": {
        "auth": "http://ab123:8080/service.jsp",
        "publish": "http://ab234:8080/service.jsp",
        "general_name": "PG1"
    }

}

当我执行以下操作时,我得到了预期的结果

jq --raw-output '."feature/EBS_DDS_SC-27428" | .auth'

但是以下方法不起作用,

export branch=feature/EBS_DDS_SC-27428
cat input.json | jq --raw-output '."${branch}" | .auth'

我收到以下编译错误:

jq: error: syntax error, unexpected '$' (Unix shell quoting issues?) at <top-level>, line 1:
.${branch} | .auth
jq: error: try .["field"] instead of .field for unusually named fields at <top-level>, line 1:
.${branch} | .auth
jq: 2 compile errors

现在我的 Linux 机器中有一个名为 branch 的环境变量

最佳答案

在您的具体情况下,我认为您有一个小的 bash 引用错误,导致 ${branch} 被视为常量。我想你想这样引用它:

     '."'      "${branch}"         '" | .auth'
     ------    ------------------  -----------
     single    double quote so     single
     quote     shell expands the   quote
     constant  branch variable     constant

示例运行

$ echo '."'"${branch}"'" | .auth'
."feature/EBS_DDS_SC-27428" | .auth

$ cat input.json | jq --raw-output '."'"${branch}"'" | .auth'
http://ab123:8080/service.jsp

Advanced Bash Scripting Guide 的变量替换部分是你的 friend 。

关于linux - jq select 动态项,其中 key 是环境变量而不是 bash 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59162608/

相关文章:

linux - 替换进程中的物理页时触发 BUG 断言

c - 直接高效读写硬盘扇区

linux - 如何使用板载键盘的击键干净地杀死 Ubuntu 板载键盘

regex - 如何删除匹配单词之间的空格?

git:仅暂存新文件

linux - 如何删除bash中的双行

linux - 在具有两个分隔符的文件中搜索值

GitLab CI 语法编写 FOR 循环语句?

json - 在使用 jq 验证 JSON 内容时结合多个测试

bash - 结果中出现重复的 id 并带有一些空值