nbari
nbari

Reputation: 26925

get objects that match a key value from a nested object that is quoted

I have a list of JSON objects with this format

[
 {
    "uuid": "2e08c71c-56af-4c1d-9677-0aad7bf38536",
    "name": "img-s3",
    "summary": "",
    "retention_name": "month",
    "retention_uuid": "beae2f1a-10e9-4b53-b9b1-baf823624ff2",
    "expiry": 2678400,
    "schedule_name": "daily",
    "schedule_uuid": "baca1a64-b506-4789-83c8-653573f2b99f",
    "schedule_when": "daily 2am",
    "paused": false,
    "store_uuid": "d91fd7b6-4c39-4f73-aa44-8ec55f52da65",
    "store_name": "default",
    "store_plugin": "s3v8",
    "store_endpoint": "{\"access_key_id\":\"xxxx\",\"bucket\":\"images-c4\",\"s3_host\":\"s3.amazon.com\",\"secret_access_key\":\"yyy\",\"signature_version\":\"2\",\"skip_ssl_validation\":true}",
    "target_uuid": "991c7aa2-cdd3-4f90-bb28-1431c99f8fc8",
    "target_name": "sc-asd",
    "target_plugin": "mysql",
    "target_endpoint": "{\"mysql_database\":\"users\",\"mysql_host\":\"10.10.22.49\",\"mysql_password\":\"password\",\"mysql_port\":\"3306\",\"mysql_user\":\"user\"}",
    "agent": "127.0.0.1:3030"
}
...
]

I need to obtain only the objects using storege_plugin: "s3v8" and that in the "quoted" value object of storage_endpoint the key signature_version is 2

To find the object having storage_plugin: "s3v8", and store_endpoing != null I am using this:

$ command | jq '.[] | select(.store_plugin == "s3v8" and .store_endpoint != null)'

But the problem I have now is that the value of store_endpoint is quoted and I only need to get results based on the value of a key, in this case, signature_value

To test how to unquote and search for the value I am trying this:

$ echo "{\"access_key_id\":\"xxxx\",\"bucket\":\"images-c4\",\"s3_host\":\"s3.amazon.com\",\"secret_access_key\":\"yyy\",\"signature_version\":\"2\",\"skip_ssl_validation\":true}" \
| jq -r 'select(.signature_version == "2")'
{
  "access_key_id": "xxxx",
  "bucket": "images-c4",
  "s3_host": "s3.amazon.com",
  "secret_access_key": "yyy",
  "signature_version": "2",
  "skip_ssl_validation": true
}

But would like to know how could I "merge" this options so that I could get a list of objects that have a set of required keys but that depends on a nested key stored on a quoted object.

Upvotes: 1

Views: 58

Answers (1)

Inian
Inian

Reputation: 85590

You need to use the fromjson construct on the nested JSON field as below. The fromjson is not so well documented in the official documentation but it allows you to parse JSON texts into values for use in filters.

.[] | select((.store_plugin == "s3v8" and .store_endpoint != null) and (.store_endpoint | fromjson | .signature_version == "2") )

jqplay.org - URL

Upvotes: 1

Related Questions