Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQ Select Objects Where Value Contains String And Value Not Null

Tags:

json

null

select

jq

Trying to select objects from JSON array where value contains a string and value is not null.

Desired output:

    {
      "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"
    }

When selecting from:

{
  "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"
    }
  ]
}

Using:

curl blah | jq ' .certificates[] | select(.variable_path|test("thing"))'

Getting:

jq: error (at <stdin>:0): null (null) cannot be matched, as it is not a string

I think the issue is that there are nulls. I am not sure how to select with the presence of these nulls without getting the error.

like image 450
Radford Avatar asked Dec 23 '22 22:12

Radford


1 Answers

One way to remove the null values from consideration would be:

.certificates[] | select(.variable_path | strings | test("thing"))

You could also consider using ?, which could be used here like this:

.certificates[] | select(.variable_path | test("thing")?)
like image 50
peak Avatar answered Dec 28 '22 09:12

peak