Home > Mobile >  jq: map field array with different length
jq: map field array with different length

Time:12-02

I'm working with those JSONs:

{
  "extension": [
    {
      "url": "url1",
      "system": "system1"
    },
    {
      "url": "url2",
      "system": "system2"
    }
  ]
}
{
  "extension": [
    {
      "url": "url3",
      "system": "system3"
    }
  ]
}

As you can see, both JSON objects have different .extension lenght.

I'm using this command in order to map input JSONs:

jq --raw-output '[.extension[] | .url, .system] | @csv'

You can find jqplay here.

I'm getting that:

"url1","system1","url2","system2"
"url3","system3"

What I would like to get is:

"url1","system1","url2","system2"
"url3","system3",,

Any ideas about how I could map those "fields" "correctly"?

CodePudding user response:

Flip the table twice using transpose | transpose to fill up the slots missing from the unrigged square shape with null:

jq -rs 'map(.extension) | transpose | transpose[] | map(.url, .system) | @csv' 
"url1","system1","url2","system2"
"url3","system3",,

Demo

CodePudding user response:

A fairly efficient solution:

def pad:
  (map(length)|max) as $mx
  | map( .   [range(length;$mx)|null] );

[inputs | [.extension[] | (.url, .system)]]
| pad[]
| @csv

This of course should be used with the -n command-line option.

  • Related