Search code examples
jsonjq

jq: get first n elements of an array field


I'm getting some issues trying to get only firsts 3 elements of an array:

json is like this:

{
   "resourceType":"Practitioner",
   "id":"328001",
   "meta":{
      "versionId":"1",
      "lastUpdated":"2021-11-08T12:47:51.239+01:00",
      "source":"#BUkX5uagwf3PcHzd"
   },
   "identifier":[
      {
         "use":"official",
         "system":"urn:oid:1.3.6.1.4.1.19126.3",
         "value":"00396185X"
      },
      {
         "use":"official",
         "system":"urn:oid:2.16.724.4.9.10.2",
         "value":"0831515"
      },
      {
         "use":"official",
         "system":"urn:oid:2.16.724.4.9.10.2",
         "value":"0831515"
      },
      {
         "use":"official",
         "system":"urn:oid:2.16.724.4.9.10.2",
         "value":"0831515"
      }
   ],
   "active":true,
   "name":[
      {
         "use":"official",
         "text":"JULIAN RODRIGUEZ LARREA",
         "family":"RODRIGUEZ",
         "_family":{
            "extension":[
               {
                  "url":"http://hl7.org/fhir/StructureDefinition/humanname-mothers-family",
                  "valueString":"LARREA"
               }
            ]
         },
         "given":[
            "JULIAN"
         ]
      }
   ],
   "qualification":[
      {
         "code":{
            "coding":[
               {
                  "system":"urn:oid:2.16.840.1.113883.6.96",
                  "code":"62247001"
               }
            ]
         }
      }
   ]
}

Is there any way to get only first 3 elements od .identifier?

jq -r '(.identifier[] | .system, .value)'

Any ideas?


Solution

  • If you are looking to print only those specific fields on the first 3 results, use the slice operator. See jqplay for demo

    .identifier[:3] | map({system, value})