3

I'm trying to extract serial number from below JSON whenever the Disabled value is true.

{
        "CertificateDetails": {
                "Serial": "1234ABCD",
                "SignatureAlgorithm": "sha256RSA"
        },
        "Disabled": true,
        "Guid": "{456767-546566-45676}"
}

Able to retrieve the value of Disabled from below query:

- name: store disabled value
  set_fact:
    Cert_Disabled: "{{ test.json | json_query('Disabled') }}"

However, as per the requirement, I would like to retrieve the Serial number only when Disabled boolean value is true. Tried below query but it isn't giving the desired result.

- name: store disabled value
  set_fact:
    Cert_Disabled: "{{ test.json | json_query('[?Disabled].CertificateDetails.Serial') }}"

1 Answer 1

2

In JMESPath, filtering can only happen on arrays, not on a single object.

So, you'll need to convert you object to an array first, with an expression using the to_array function:

to_array(@)

Then, you can come back to a simple object, after stopping the projection created by the filter, with the help of the pipe expression:

to_array(@)[?Disabled] | [0]

And finally select the property you want:

to_array(@)[?Disabled] | [0].CertificateDetails.Serial

Which, in this case gives you 1234ABCD but that would give a null if the Disabled field is false.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.