jq recipes
I never remember how to do things with jq. Hopefully some sort of mental model emerges from these recipes.
Formatting JSON data
jq has a set of string formatting and escaping filters.
To convert an array to CSV or TSV, pick the properties you’re interested in and apply the @csv
or @tsv
filters:
jq -r '.[] | [.href, .title] | @tsv' links.json
You can also do string interpolation to build XML/HTML:
jq -r '.[] | "<p><a href=\"\(.href)\">\(.description | @html)</a><p><blockquote>\(.extended | @html)</blockquote><p>\(.tags | @html)</p>"'
- the several levels of nested quotes means we need to escape the last level of double quotes;
- note the usage of the
@html
escape filter that prevents interpolated values from breaking the markup.