jq:无法使用jq从Json文件中检索键/值



我从curl输出中得到了下面的JSON,我需要从中检索IP地址。我尝试了下面的jq查询,但收到了下面的错误。我尝试了其他几种方法,但没有成功

curl -sH "X-Requested-By: ambari" -u admin:admin -i http://${AMBARI_IP}:8080/api/v1/hosts?fields=Hosts/host_name,Hosts/ip | jq '.[] | {.items.Hosts.ip}'

jq: error: syntax error, unexpected FIELD (Unix shell quoting issues?) at <top-level>, line 1:
.[] | {.items.Hosts.ip}
jq: 1 compile error
(23) Failed writing body

下面是卷曲的输出

HTTP/1.1 200 OK
Date: Fri, 02 Jul 2021 21:04:27 GMT
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Cache-Control: no-store
Pragma: no-cache
Set-Cookie: AMBARISESSIONID=123344.node0;Path=/;HttpOnly
Expires: Thu, 01 Jan 1970 00:00:00 GMT
User: admin
Content-Type: text/plain;charset=utf-8
X-Content-Type-Options: nosniff
Vary: Accept-Encoding, User-Agent
Transfer-Encoding: chunked
{
"href" : "http://10.0.0.33:8080/api/v1/hosts?fields=Hosts/host_name,Hosts/ip",
"items" : [
{
"href" : "http://10.0.0.33:8080/api/v1/hosts/sil.dev.test.com",
"Hosts" : {
"host_name" : "test123.sil.dev.test.com",
"ip" : "10.135.3.119"
}
},
{
"href" : "http://10.0.0.33:8080/api/v1/hosts/test001.sil.dev.test.com",
"Hosts" : {
"cluster_name" : "test_cluster",
"host_name" : "test001.sil.dev.test.com",
"ip" : "10.0.0.33"
}
},
{
"href" : "http://10.0.0.33:8080/api/v1/hosts/test002.sil.dev.test.com",
"Hosts" : {
"cluster_name" : "test_cluster",
"host_name" : "test002.sil.dev.test.com",
"ip" : "10.0.0.34"
}
},
{
"href" : "http://10.0.0.33:8080/api/v1/hosts/test003.sil.dev.test.com",
"Hosts" : {
"cluster_name" : "test_cluster",
"host_name" : "test003.sil.dev.test.com",
"ip" : "10.0.0.35"
}
},
}

尝试jq '.items[].Hosts.ip'。这从外部对象获取.items键,迭代items数组,然后从每个对象的路径.Hosts.ip中提取值。

PS > cat a.json
{
"href" : "http://10.0.0.33:8080/api/v1/hosts?fields=Hosts/host_name,Hosts/ip",
"items" : [
{
"href" : "http://10.0.0.33:8080/api/v1/hosts/sil.dev.test.com",
"Hosts" : {
"host_name" : "test123.sil.dev.test.com",
"ip" : "10.135.3.119"
}
},
{
"href" : "http://10.0.0.33:8080/api/v1/hosts/test001.sil.dev.test.com",
"Hosts" : {
"cluster_name" : "test_cluster",
"host_name" : "test001.sil.dev.test.com",
"ip" : "10.0.0.33"
}
},
{
"href" : "http://10.0.0.33:8080/api/v1/hosts/test002.sil.dev.test.com",
"Hosts" : {
"cluster_name" : "test_cluster",
"host_name" : "test002.sil.dev.test.com",
"ip" : "10.0.0.34"
}
},
{
"href" : "http://10.0.0.33:8080/api/v1/hosts/test003.sil.dev.test.com",
"Hosts" : {
"cluster_name" : "test_cluster",
"host_name" : "test003.sil.dev.test.com",
"ip" : "10.0.0.35"
}
}
]
}
PS > cat a.json | jq '.items[].Hosts.ip'
"10.135.3.119"
"10.0.0.33"
"10.0.0.34"
"10.0.0.35"
PS > cat a.json | jq -r '.items[].Hosts.ip'
10.135.3.119
10.0.0.33
10.0.0.34
10.0.0.35

最新更新