使用Google Cloud REST API获取实例列表时jq过滤报错求助
jq解析Google Cloud实例JSON时的错误修复
问题描述
我通过Google Cloud REST API获取了所有计算实例列表并保存到file.json,执行命令:
cat file.json | jq .items.zones/me-west1-c
时出现以下错误:
jq: error: me/0 is not defined at
, line 1:
.items.zones/me-west1-c
jq: error: west1/0 is not defined at, line 1:
.items.zones/me-west1-c
jq: error: c/0 is not defined at, line 1:
.items.zones/me-west1-c
错误原因
- jq中
/是除法运算符,不是路径分隔符,你写的.items.zones/me-west1-c会被jq当成除法运算,直接触发语法错误。 - Google Cloud实例的JSON结构里,区域字段是
zone(单数),不是zones;同时items是数组类型,必须用[]遍历数组元素,才能访问每个实例的具体字段。
正确命令写法
根据你的实际需求选择对应的命令:
筛选出位于
me-west1-c区域的所有实例:cat file.json | jq '.items[] | select(.zone | endswith("me-west1-c"))'(注:
zone字段值是完整资源路径,格式类似projects/xxx/zones/me-west1-c,用endswith匹配末尾的区域名更准确)仅提取所有实例的区域信息:
cat file.json | jq '.items[].zone'
内容的提问来源于stack exchange,提问作者Kalyan
相关产品推荐
相关产品推荐

