Search code examples
jsonformattingjq

Print a JSON array in human readable format using jq


I am relatively not experienced in jq, so the answer may be very simple, but I couldn't find it on the Internet somehow.

I have a JSON array like this:

[
 {
  "key1": "value1a",
  "key2": "value2a",
  "key3": "value3a",
  "keyn": "valuena"
 },
 {
  "key1": "value1b",
  "key2": "value2b",
  "key3": "value3b",
  "keyn": "valuenb"
 },
 {
  "key1": "value1z",
  "key2": "value2z",
  "key3": "value3z",
  "keyn": "valuenz"
 }
]

And I want to print it in the following "human-readable" format:

key1 : value1a
key2 : value2a
key3 : value3a
keyn : valuena

key1 : value1b
key2 : value2b
key3 : value3b
keyn : valuenb

key1 : value1z
key2 : value2z
key3 : value3z
keyn : valuenz

using preferably jq command.

Note that the number of elements of the array and the number of key/value pairs for each element is variable and not known in advance.


Solution

  • If you don't mind an empty line at the end of the output, this should work fine:

    jq -r '.[] | (to_entries[] | "\(.key) : \(.value)"), ""'
    

    Online demo