【问题标题】:Pass shell variable to JQ and build a key name using it将 shell 变量传递给 JQ 并使用它构建一个键名
【发布时间】:2021-03-27 23:10:22
【问题描述】:

我需要执行cat build.json | jq '.Stage*.Name' 5 次,其中* 是一个从1 到5 的数字。

我试过了:

for (( c=1; c<5; c++ ))
do
  echo $c
  cat build.json | jq '.Stage${c}.Name'
done

我得到了这个错误:

jq: error: syntax error, unexpected '$', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.Stage${c}.Name      
jq: 1 compile error

我该如何正确地做到这一点?

【问题讨论】:

  • 我不确定你是否真的需要一个 shell 循环。实际任务是什么?
  • 为了记录,你需要双引号才能工作;但是使用--arg 是一个更好的解决方案。另见stackoverflow.com/questions/6697753/…

标签: json bash shell key jq


【解决方案1】:

考虑以下 json 文件 (./json.json):

{
    "data": {
        "stage1": {
            "name": 1
        },
        "stage2": {
            "name": 2
        },
        "stage3": {
            "name": 3
        },
        "stage4": {
            "name": 4
        },
        "stage5": {
            "name": 5
        }
    }
}

通过此设置,您可以使用 的 arg 解析您的迭代器:

#!/bin/bash
for (( i = 1; i <= 5; i++ )); do
    echo "i: $i"
    jq --arg i $i '.data.stage'$i'.name' < json.json
done

产生以下输出:

i: 1
1
i: 2
2
i: 3
3
i: 4
4
i: 5
5

passing arguments to jq filter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多