JQ选择值包含字符串且值不为空的对象
Posted
技术标签:
【中文标题】JQ选择值包含字符串且值不为空的对象【英文标题】:JQ Select Objects Where Value Contains String And Value Not Null 【发布时间】:2019-11-03 12:55:28 【问题描述】:尝试从 JSON 数组中选择值包含字符串且值不为空的对象。
期望的输出:
"configurable": false,
"property_reference": ".properties.blobstore_certificate",
"property_type": "rsa_cert_credentials",
"product_guid": "p-blah-29d4678e926cf2069871",
"location": "ops_manager",
"variable_path": "something",
"issuer": "/C=US/O=Blah",
"valid_from": "2019-01-16T19:55:11Z",
"valid_until": "2021-01-16T19:55:11Z"
选择时:
"certificates": [
"configurable": false,
"property_reference": ".properties.director_ssl",
"property_type": "rsa_cert_credentials",
"product_guid": "p-blah-29d4678e926cf2069871",
"location": "ops_manager",
"variable_path": null,
"issuer": "/C=US/O=Blah",
"valid_from": "2019-01-16T19:55:10Z",
"valid_until": "2021-01-16T19:55:10Z"
,
"configurable": false,
"property_reference": ".properties.uaa_ssl",
"property_type": "rsa_cert_credentials",
"product_guid": "p-blah-29d4678e926cf2069871",
"location": "ops_manager",
"variable_path": null,
"issuer": "/C=US/O=Blah",
"valid_from": "2019-01-16T19:55:10Z",
"valid_until": "2021-01-16T19:55:10Z"
,
"configurable": false,
"property_reference": ".properties.blobstore_certificate",
"property_type": "rsa_cert_credentials",
"product_guid": "p-blah-29d4678e926cf2069871",
"location": "ops_manager",
"variable_path": "something",
"issuer": "/C=US/O=Blah",
"valid_from": "2019-01-16T19:55:11Z",
"valid_until": "2021-01-16T19:55:11Z"
]
使用:
curl blah | jq ' .certificates[] | select(.variable_path|test("thing"))'
获取:
jq: error (at <stdin>:0): null (null) cannot be matched, as it is not a string
我认为问题在于存在空值。我不确定如何在存在这些空值的情况下进行选择而不会出现错误。
【问题讨论】:
【参考方案1】:从考虑中删除null
值的一种方法是:
.certificates[] | select(.variable_path | strings | test("thing"))
你也可以考虑使用?
,在这里可以这样使用:
.certificates[] | select(.variable_path | test("thing")?)
【讨论】:
如果我只使用| strings
,它会返回包含字符串的对象,但测试管道似乎不起作用,所以我没有得到任何输出。
我已经仔细检查过了。你有没有抄错或放错括号?您是否尝试过这两种解决方案?以上是关于JQ选择值包含字符串且值不为空的对象的主要内容,如果未能解决你的问题,请参考以下文章