Search code examples
jsonerror-handlingjqexport-to-csv

how to display specific array of arrays elements matching pattern


I have the following array, with thoushand json elements, like the following

[
  {                                                                                                                                                                                                                                     
    "id": 302,
    "hostname": "laptop857",
    "total_memory": 31722,
    "total_swap": 92535,
    "distribution": "22.04",
    "hardware": [
      [
        "product",
        "XPS 15 7590 (0905)",
        null
      ],
      [
        "vendor",
        "Dell Inc.",
        null
      ],
      [
        "serial",
        "XXDPXXX",
        null
      ]
    ]
  }
  {
    "id": 303,
    "hostname": "laptop858",
  ....
  }, 
]

My goal is to parse the json file and for each elements extract the hostname, distribution and serial number. I want to create a report where each line represent a computer, like laptop857,22.04,XXDPXXX laptop858, ....

I'm able to output for hostname and distribution , together I'm also able to do it for serial, but some entries do not have serial number and failed the parsing I keep getting error for whatever I try to get the 3 elements together on the same line

Any chance someone could provide hit or what I should look at to achieve my result I could live with an entry like laptop857,22.04,serial XXDPXXX null


Solution

  • You can suppress errors caused by non-existing parts by using ?, and provide a default alternative using //. For example:

    .[] | [
      .hostname,
      .distribution,
      first(.hardware[] | select(.[0] == "serial") | .[1])? // "n/a"
    ] | @csv
    

    Demo