Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jq: where select clause is applied

Here my documents:

[
   {
      "id":"f3b8c257-9950-45e7-9e79-ace19ec8905e",
      "identifier":[
         {
            "system":{
               "value":"urn:oid:2.16.724.4.9.10.2"
            },
            "value":{
               "value":"10839812"
            }
         }
      ]
   },
   {
      "id":"f0a1e3ae-826f-4a03-b29e-10ef3bc86ea0",
      "identifier":null
   }
]

Currently, I’m aplying this jq filter:

map(
    {
        id,
        dni: .identifier[] | (select(.system.value == "urn:oid:1.3.6.1.4.1.19126.3") | .value.value)
    }
)

However, I’m getting this message:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

jq: error (at practitioner-mongoexport.json:146715): Cannot iterate over null (null)

As you can guess, problem arises processing second object where .identifier: null.

I’ve tried with that:

map(
    {
        id,
        dni: select(.identifier) | .identifier[] | (select(.system.value == "urn:oid:1.3.6.1.4.1.19126.3") | .value.value)
    }
)

I’ve also tried with:

map(
    select(.identifier) |
    {
        id,
        dni: .identifier[] | (select(.system.value == "urn:oid:1.3.6.1.4.1.19126.3") | .value.value)
    }
)

Then result is [].

I don’t quite figure out what I’m doing wrong.

My desired output would be:

[
   {
      "id":"f3b8c257-9950-45e7-9e79-ace19ec8905e",
      "dni": "10839812"
   }
]

Any ideas?

>Solution :

map(
    select(.identifier?[]?.system.value == "urn:oid:2.16.724.4.9.10.2") 
    | { id, "dni": .identifier[].value.value }
)

Will generate:

[
  {
    "id": "f3b8c257-9950-45e7-9e79-ace19ec8905e",
    "dni": "10839812"
  }
]

The trick here is .identifier?[]?.system.value where the ? will ignore .identifier if it’s null


JqPlay Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading