将 shell 变量传递给 JQ 并使用它构建一个键名
Pass shell variable to JQ and build a key name using it
我需要执行5次cat build.json | jq '.Stage*.Name'
,其中*
是一个从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
如何正确执行此操作?
考虑以下 json 文件 (./json.json
):
{
"data": {
"stage1": {
"name": 1
},
"stage2": {
"name": 2
},
"stage3": {
"name": 3
},
"stage4": {
"name": 4
},
"stage5": {
"name": 5
}
}
}
使用此设置,您可以使用 jq 的参数来解析您的迭代器:
#!/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
我需要执行5次cat build.json | jq '.Stage*.Name'
,其中*
是一个从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
如何正确执行此操作?
考虑以下 json 文件 (./json.json
):
{
"data": {
"stage1": {
"name": 1
},
"stage2": {
"name": 2
},
"stage3": {
"name": 3
},
"stage4": {
"name": 4
},
"stage5": {
"name": 5
}
}
}
使用此设置,您可以使用 jq 的参数来解析您的迭代器:
#!/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