Skip to content

Instantly share code, notes, and snippets.

@CodeShane
Forked from talwrii/jqcheatsheet.md
Last active November 22, 2018 21:44
Show Gist options
  • Save CodeShane/dc083558f39ad1b722fc9bbc72f6f9fa to your computer and use it in GitHub Desktop.
Save CodeShane/dc083558f39ad1b722fc9bbc72f6f9fa to your computer and use it in GitHub Desktop.
jq cheatsheet

jq cheatsheet

Extract field from list of objects

jq 'map(.foo)'

[ { foo: 1 }, { foo: 2 } ]
[1, 2]

Extract as stream of values instead of a list

jq '.[] | .foo'

[ { foo: 1 }, { foo: 2 } ]
1, 2

Slicing

jq '.[1:2]'

[ { foo: 1 }, { foo: 2 } ]
{ foo: 2 }

Dictionary subset shorthand

jq 'map({ a, b })'

[ { a: 1, b: 2, c: 3 }, ...]
[ { a: 1, b: 2 }, ...]

jq 'with_entries(.value |= fromjson)' --sort-keys

Parsing json

{ b: "{}", a: "{}" }
{ a: {}, b: {} }

Serializing json

jq 'with_entries(.value |= tojson)' --sort-keys

{ a: {}, b: {} }
{ a: "{}", b: "{}" }

Flattening json

jq 'flatten(1)'

[[1], [2]]
[1, 2]

Converting to csv

jq '.[] | [.foo, .bar] | @csv' -r

[{ "foo": 1, "bar": 2, "baz":3 }]
1,2

Sort

jq 'sort'

[3, 2, 1]
[1, 2, 3]

Deleting duplicates (dedup / uniq)

jq unique

[1, 1, 2, 1]
[1, 2]

Sort lines of a file

jq --slurp '. | sort | .[]'

Converting arbitrary data to json

jq -r '(map(keys) | add | unique | sort) as $cols | .[] as $row | $cols | map($row[.]) | @csv'

[ { "foo": 1, "bar": 2}, { "foo": 3, "baz": 4}]
2,,1
,4,3

Convert an array to a stream of json records one per line

jq -rc '.[]'

Suitable for stream. See record stream



Extract only some attributes from a list of objects

jq '.[] | {attribute1, attribute2}'

Filter this by attribute

jq '.[] | select(attribute1 == "") | {attribute1, attribute2}'

Raw output

jq -r '{query}' # raw output, strips quotes et al. good for pipelining into grep. jq -r 'keys | .[]' # lists just the keys of a map

Json Tools

jq - obviously

jsonpath -

gron - greppable JSON encoder/decoder - https://github.com/tomnomnom/gron

Sources

Upstream was adapted from SO (http://bit.ly/2fOwzRR) https://gist.github.com/mikepea/4ef65dacd760aeaeb7f8bd8abb85a127 http://lzone.de/cheat-sheet/jq

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment