Home > Software engineering >  Jq: map fields to csv
Jq: map fields to csv

Time:11-20

I need to map and convert a json file to csv.

This is my file. Take in mind, it's not an array. Each element is in a row.

{
   "resourceType":"PractitionerRole",
   "id":"2261026",
   "meta":{
      "versionId":"1",
      "lastUpdated":"2021-11-08T15:13:39.318 01:00",
      "source":"#wcktDPNPRW67Ths4"
   },
   "identifier":[
      {
         "system":"urn:oid:2.16.724.4.9.20.93",
         "value":"6209"
      },
      {
         "system":"urn:oid:2.16.724.4.9.20.2",
         "value":"00042"
      },
      {
         "system":"urn:oid:2.16.724.4.9.20.90",
         "value":"UAB2"
      }
   ],
   "active":true,
   "practitioner":{
      "reference":"Practitioner/1046220"
   },
   "code":[
      {
         "coding":[
            {
               "system":"http://catsalut.gencat.cat/fhir/StructureDefinition/tipus-rol-professional",
               "code":"MG"
            }
         ]
      }
   ]
}
{
   "resourceType":"PractitionerRole",
   "id":"2261027",
   "meta":{
      "versionId":"1",
      "lastUpdated":"2021-11-08T15:13:39.140 01:00",
      "source":"#l6DwTkxasiJQmfBJ"
   },
   "identifier":[
      {
         "system":"urn:oid:2.16.724.4.9.20.93",
         "value":"6734"
      },
      {
         "system":"urn:oid:2.16.724.4.9.20.2",
         "value":"01785"
      },
      {
         "system":"urn:oid:2.16.724.4.9.20.91",
         "value":"IN013"
      }
   ],
   "active":true,
   "practitioner":{
      "reference":"Practitioner/1045804"
   },
   "code":[
      {
         "coding":[
            {
               "system":"http://catsalut.gencat.cat/fhir/StructureDefinition/tipus-rol-professional",
               "code":"INF"
            }
         ]
      }
   ]
}

I need to get those fields:

.id, .meta.lastUpdated, .identifier[0].value, .identifier[1].value, .identifier[2].value, .code[0].coding[0].code

And extract them as id, lastUpdated, identifier1, identifier2, identifier3, code in csv format.

Any ideas?

CodePudding user response:

You can construct an array and then use @csv directly:

$ jq -r '[.id,.meta.lastUpdated,.identifier[0].value,.identifier[1].value,.identifier[2].value,.code[0].coding[0].code] | @csv' file.txt
"2261026","2021-11-08T15:13:39.318 01:00","6209","00042","UAB2","MG"
"2261027","2021-11-08T15:13:39.140 01:00","6734","01785","IN013","INF"
  • Related