Json JQ选择存在内部键的对象
仅当密钥Json JQ选择存在内部键的对象,json,object,filter,jq,Json,Object,Filter,Jq,仅当密钥credhub ref存在于以下JSON中时,我才尝试选择凭证对象: { "total_results": 23, "total_pages": 1, "prev_url": null, "next_url": null, "resources": [ { "entity": { "credentials": {}, "binding_options": {},
credhub ref
存在于以下JSON中时,我才尝试选择凭证对象:
{
"total_results": 23,
"total_pages": 1,
"prev_url": null,
"next_url": null,
"resources": [
{
"entity": {
"credentials": {},
"binding_options": {},
"gateway_data": null,
"gateway_name": "",
"syslog_drain_url": null,
"volume_mounts": [],
"name": null,
"last_operation": {
"type": "create",
"state": "succeeded",
"description": "",
"updated_at": "2018-10-15T19:13:57Z",
"created_at": "2018-10-15T19:13:57Z"
},
"app_url": "/v2/3"
}
},
{
"entity": {
"app_guid": "sd",
"service_instance_guid": "sd",
"credentials": {
"hostname": "w",
"port": 3306
},
"binding_options": {},
"gateway_data": null,
"gateway_name": "",
"syslog_drain_url": null,
"volume_mounts": [],
"name": null,
"last_operation": {
"type": "create",
"state": "succeeded",
"description": "",
"updated_at": "2018-10-15T19:24:06Z",
"created_at": "2018-10-15T19:24:06Z"
},
"app_url": "/v2/3"
}
},
{
"entity": {
"credentials": {
"credhub-ref": "ref3"
},
"binding_options": {},
"gateway_data": null,
"gateway_name": "",
"syslog_drain_url": null,
"volume_mounts": [],
"name": null,
"last_operation": {
"type": "create",
"state": "succeeded",
"description": "",
"updated_at": "2019-03-19T20:07:27Z",
"created_at": "2019-03-19T20:07:27Z"
},
"app_url": "/v2/45"
}
},
{
"entity": {
"credentials": {
"credhub-ref": "ref4"
},
"binding_options": {},
"gateway_data": null,
"gateway_name": "",
"syslog_drain_url": null,
"volume_mounts": [],
"name": null,
"last_operation": {
"type": "create",
"state": "succeeded",
"description": "",
"updated_at": "2019-03-19T20:07:27Z",
"created_at": "2019-03-19T20:07:27Z"
},
"app_url": "/v2/45"
}
}
]
}
当我使用cat my_bindings_test2.json | jq'.resources[]|.entity.credentials'
时,我得到:
{}
{
"hostname": "w",
"port": 3306
}
{
"credhub-ref": "ref3"
}
{
"credhub-ref": "ref4"
}
使用JQ,我将如何得到以下结果
{
"credhub-ref": "ref3"
}
{
"credhub-ref": "ref4"
}
像这样:
jq '.resources[].entity.credentials|select(has("credhub-ref"))' file.json
如果保证
credhub ref
不会为null
或false
,则可以使用select(.[credhub ref]])
:
否则请参考@hek2mgl的答案。谢谢。刚到jq的我今天好几次都很亲近。我使用的是
jq'.resources[].entity.credentials | select(.credhub ref)'my_bindings_test.json
Welcome。当keyname包含不明确的字符时,可以使用[“keyname”]
符号说明:如果“credhub ref”为null
或false
,则不会产生输出。不确定这是否是你想要的。这个问题的正确答案是使用has(“credhub-ref”)
——正如我所展示的;)NP做得好!PS:null
和false
似乎是jq中唯一的“falsish”值-与javascript相反。这是个好消息!我从来都不确定,谢谢。这个值永远不应该为false或null,但我很高兴您提到了这一点,因为我打算将其推广以备将来使用。
jq '.resources[].entity.credentials | select(.["credhub-ref"])' file