JQ选择内部键存在的对象

时间:2019-03-19 23:50:35

标签: json object filter jq

仅当密钥{ "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" } } ] } 存在于以下JSON中时,我才尝试选择凭据对象:

cat my_bindings_test2.json |  jq '.resources[] | .entity.credentials'

使用{} { "hostname": "w", "port": 3306 } { "credhub-ref": "ref3" } { "credhub-ref": "ref4" } 时,我得到:

{
  "credhub-ref": "ref3"
}
{
  "credhub-ref": "ref4"
}

使用JQ,我将如何获得以下结果?

=IF(OR(ISBLANK(A2),ISBLANK(B2)), 0, 1)

3 个答案:

答案 0 :(得分:1)

或者,您可以考虑使用简单的unix实用程序 jtc 遍历JSON:

bash $ <file.json jtc -w'<credhub-ref>l:[-1]'
{
   "credhub-ref": "ref3"
}
{
   "credhub-ref": "ref4"
}
bash $ 

答案 1 :(得分:1)

赞:

jq '.resources[].entity.credentials|select(has("credhub-ref"))' file.json

答案 2 :(得分:1)

如果保证不会credhub-refnull,则可以使用false

select(.["credhub-ref"])

否则请参考@ hek2mgl的答案。