2

I am trying to get jq to render a json object into tsv format. I came across a way to generate headers dynamically using the key name.

I am getting this error:

object ({"version":...) is not valid in a csv row

I am guessing this is due to some fields being arrays: Installed and Latest. How can I make this work with those fields? Also, why is my output including \t?

Current Output:

"RELEASE\tINSTALLED\tLATEST\tOUTDATED\tDEPRECATED"
jq: error (at <stdin>:28): object ({"version":...) is not valid in a csv row

Desired output:

RELEASE         INSTALLED    LATEST    OUTDATED      DEPRACATED
test-app        1.0.0        2.0.0     true          false    
test-app2       3.0.0        3.5.0     true          false 

jq

cat test1.json | jq '[.[]| with_entries( .key |= ascii_upcase ) ] | (.[0] |keys_unsorted | @tsv), (.[]|.|map(.) |@tsv)'

json:

[
  {
    "release": "test-app",
    "Installed": {
      "version": "1.0.0",
      "appVersion": ""
    },
    "Latest": {
      "version": "2.0.0",
      "appVersion": ""
    },
    "outdated": true,
    "deprecated": false
  },
  {
    "release": "test-app2",
    "Installed": {
      "version": "3.0.0",
      "appVersion": ""
    },
    "Latest": {
      "version": "3.5.0",
      "appVersion": ""
    },
    "outdated": true,
    "deprecated": false
  }
]
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MaryCoding
  • 624
  • 1
  • 9
  • 31

1 Answers1

5

The first thing is to get your ducks in a row:

map({release, installed: .Installed.version, latest: .Latest.version, deprecated})

Now the headers are easy:

( .[0] | keys_unsorted | map(ascii_upcase))

... and it's safe to use .[] to fetch the values:

.[] | [.[]]

Putting it all together:

map({release, installed: .Installed.version, latest: .Latest.version, deprecated})
| ( .[0] | keys_unsorted | map(ascii_upcase)),
  (.[] | [.[]])
| @tsv

A line of dashes under the headers

In your related question at Jq tsv error in formatting an array/object, you required a line of dashes under the headers.

To automate the production of such a line, see How to format a JSON string as a table using jq?

peak
  • 105,803
  • 17
  • 152
  • 177