Search code examples
jsonnulljqdefaultifempty

jq: pick null instead of empty


I've created this filter expression:

def pick_extension($url):
   .extension[] | select( .url == $url);

[
    ( pick_extension( "http://hl7.org/fhir/StructureDefinition/patient-nationality" ) | .url, ( .extension[0] | .url, ( .valueCodeableConcept.coding[0] | .system, .code ) ) )
]

Issue is that when pick_extension(url) doesn't pick any object, it returns empty.

Then other piped expression are empty as well.

Currently, I'm getting empty arrays:

[]
[]
[]

Desired output I need would be:

[null, null, null, null]
[null, null, null, null]
[null, null, null, null]
...

Currently, I'm working with it in this jqplay.

Here some json extracted json input object:

{
   "resourceType":"Patient",
   "id":"14426955",
   "meta":{
      "versionId":"1",
      "lastUpdated":"2021-12-01T14:24:11.387+01:00",
      "source":"#XbZyfGxZj4fZygTv"
   },
   "extension":[
      {
         "url":"http://hl7.org/fhir/StructureDefinition/patient-nationality",
         "extension":[
            {
               "url":"code",
               "valueCodeableConcept":{
                  "coding":[
                     {
                        "system":"urn:iso:std:iso:3166",
                        "code":"724"
                     }
                  ]
               }
            }
         ]
      },
      {
         "url":"http://catsalut.gencat.cat/fhir/StructureDefinition/patient-status",
         "valueCodeableConcept":{
            "coding":[
               {
                  "system":"http://catsalut.gencat.cat/fhir/EstatRegistre",
                  "code":"alta"
               }
            ]
         }
      }
   ]
}

Solution

  • // {"url":null} works for me:

    def pick_extension($url):    .extension[] | select( .url == $url);  [  (( pick_extension( "http://catsalut.gencat.cat/fhir/StructureDefinition/patient-occupation" ) // {"url":null})  | .url , ( .valueCodeableConcept.coding[0] | .system, .code) ) ] 
    

    https://jqplay.org/s/QlVGUer8Nu