Home > Back-end >  Translate JSON into Markdown list with jq
Translate JSON into Markdown list with jq

Time:12-04

I've got a JSON structure for projects and tasks:

{
  "project1": [
    "task1a",
    "task1b"
  ],
  "project2": [
    "task2a",
    "task2b",
    "task2c"
  ]
}

which I'd like to convert to MD-like list:

* project1
  * task1a
  * task1b
* project2
  * task2a
  * task2b
  * task2c

mainly using jq and sh/bash

the best I can do is:

jq '. | to_entries | .[] | .value |= "  * " join("\n  * ") "\n" | .key = "* " .key'

but then I'm stuck trying to properly print .value string along with .key

CodePudding user response:

Yet another solution, without the update operator |=, without the join() builtin and without explicit newline characters \n:

jq -r 'to_entries[] | "* \(.key)", "  * \(.value[])"'
* project1
  * task1a
  * task1b
* project2
  * task2a
  * task2b
  * task2c

Demo

CodePudding user response:

Another solution, using join() and string interpolation:

to_entries[] | "* \(.key)\n  * \(.value | join("\n  * "))"

Will produce:

* project1
  * task1a
  * task1b
* project2
  * task2a
  * task2b
  * task2c
jq -r 'to_entries[] | "* \(.key)\n  * \(.value | join("\n  * "))"' input
JqPlay Demo

CodePudding user response:

You're very close. Add -r to output raw strings instead of JSON, and use | .key, .value to output the key and value strings as separate items so they are shown on adjacent lines.

jq -r '. | to_entries | .[] | .value |= "  * " join("\n  * ") | .key = "* " .key | .key, .value'
  • Related