JQ:通过键变量访问对象
JQ: access object by key variable
假设我有一个对象 'variables' 包含可变数量的未指定的其他对象:
{
"id":5,
"variables":{
"variable1":{
"isSecret":null,
"value":"value1"
},
"variable2":{
"isSecret":null,
"value":"value2"
}
}
}
我需要的是一种在同一循环中访问键名和 'value' 值的方法。
我尝试了以下方法:
echo $service_connection | jq -r '.variables | keys[]' | while read variable; do
echo $variable
echo $service_connection | jq --arg var "$variable" -c '.variables[$var].value'
done
这给了我以下输出:
variable1
null
variable2
null
对我来说,似乎我需要类似
的东西
'.variables.$var'
或
'.variables.[$var]'
但是jq无法解析
我做错了什么?
您不需要 bash 干预 while
读取循环,用 jq
完成所有操作
jq -r '.variables | keys_unsorted[] as $k | "\($k) \(.[$k].value)"'
产生的结果为
variable1 value1
variable2 value2
使用 to_entries
将 .variables
对象拆分为 key-value 对数组也是一种选择:
jq -r '.variables | to_entries[] | "\(.key): \(.value.value)"'
variable1: value1
variable2: value2
假设我有一个对象 'variables' 包含可变数量的未指定的其他对象:
{
"id":5,
"variables":{
"variable1":{
"isSecret":null,
"value":"value1"
},
"variable2":{
"isSecret":null,
"value":"value2"
}
}
}
我需要的是一种在同一循环中访问键名和 'value' 值的方法。
我尝试了以下方法:
echo $service_connection | jq -r '.variables | keys[]' | while read variable; do
echo $variable
echo $service_connection | jq --arg var "$variable" -c '.variables[$var].value'
done
这给了我以下输出:
variable1
null
variable2
null
对我来说,似乎我需要类似
的东西'.variables.$var'
或
'.variables.[$var]'
但是jq无法解析
我做错了什么?
您不需要 bash 干预 while
读取循环,用 jq
jq -r '.variables | keys_unsorted[] as $k | "\($k) \(.[$k].value)"'
产生的结果为
variable1 value1
variable2 value2
使用 to_entries
将 .variables
对象拆分为 key-value 对数组也是一种选择:
jq -r '.variables | to_entries[] | "\(.key): \(.value.value)"'
variable1: value1
variable2: value2