Skip to content

jq examples and tutorial

John Bogovic edited this page May 10, 2023 · 7 revisions

https://jqplay.org/

example data

arr.jsonhttps://github.com/saalfeldlab/n5-ij/wiki/jq-examples-and-tutorial/_edit
[0,1,2,3,4]
obj.json
{
    "one" : 1,
    "two" : 2,
    "twelve" : 12
}
obj_obj.json
{
    "one" : {
        "roman" : "i",
        "primes" : []
    },
    "two" : {
        "roman" : "ii",
        "primes" : [2]
    },
    "twelve" : {
        "roman" : "xii",
        "primes" : [2,2,3]
    },
    "sixty" : {
        "decimal" : 60,
        "roman" : "xii",
        "primes" : [2,2,3,5]
    }
}

basics

Index and slice an array

jq '.' arr.json
jq '.[2]' arr.json
jq '.[0:2]' arr.json
jq '.[1] + .[3]' arr.json
jq '.[]' arr.json
jq '.three?' arr.json
jq '. + [12] | .[1] + .[5]' arr.json

Index and slice an object

jq '.' obj.json
jq '.["one"]' obj.json
jq '.one' obj.json
jq '.one + .twelve' obj.json
jq '.[]' obj.json
jq '.three?' obj.json
jq '.seven = 7' obj.json
jq '.twelve = "xii"' obj.json

Simple string manipulation

jq -n '"hello" + "world"'
jq -n '["hello","world"] | join("_")'

more object indexing and assignment

jq '.one = [1,"one","i"]' obj.json
jq '.one |= [.] + ["one","i"] | .one | .[1]' obj.json
jq '.one |= [.] + ["one","i"] | .one[1]' obj.json

map, select, group_by

and conditionals

jq 'map(. + 1)' arr.json
jq 'map(. * 2)' arr.json
jq 'map(if . % 2 == 0 then 1 else -1 end)' arr.json

group_by

jq -n 'range(20) | group_by( . % 4 )'

select; arrays vs streams

jq -n '[range(20)] | map( select( . % 3 == 0 ))'
jq -n 'range(20) | select( . % 3 == 0 )'

map_values and object merging

jq '.[0] | map_values({decimal: .} )' obj.json
jq -s '(.[0] | map_values({decimal: .} )) * .[1]' obj.json obj_obj.json

functions and variables

jq 'def avg: length as $N | add / $N; avg' arr.json
jq 'def avg: | add / length; avg' arr.json
jq -n 'def sum( $v ): . + $v; 5 | sum(3)'

reduce

reduce .[] as $i (1; . * $i)' arr.json

include

jq -n 'include "fact"; 4 | fact'
jq -n 'include "fib"; [range(10)] | map(fib)'

other technical stuff

jq 'type' obj.json
jq 'type' arr.json
jq -n '1 | type'
jq -n '"a" | type'

jq -n '{a:1} | has("a")'
jq -n '{a:1} | has("b")'

recurse and walk

jq '..' obj.json
jq '.one |= [.] + ["one","i"] | ..' obj.json
jq '.one |= [.] + ["one","i"] | walk( if type == "number" then . + 1 else . end)' obj.json