2

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.

FedKad
  • 493
  • 4
  • 19
  • Does this help? [How to convert a JSON object to key=value format in jq?](https://stackoverflow.com/questions/25378013/how-to-convert-a-json-object-to-key-value-format-in-jq) – oguz ismail Aug 23 '21 at 13:00
  • Thanks for your comment. That's almost 90% in the right direction. The only missing part is: How can I add an empty line between different array elements? – FedKad Aug 23 '21 at 13:10
  • Okay, let me post an answer then. – oguz ismail Aug 23 '21 at 13:10

2 Answers2

1

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

oguz ismail
  • 1
  • 16
  • 47
  • 69
1

One way to avoid the extra newline is to use join twice:

[.[]
 | [ (to_entries[] | "\(.key) : \(.value)}") ]
   | join("\n")]
| join("\n\n")
peak
  • 105,803
  • 17
  • 152
  • 177