-
Notifications
You must be signed in to change notification settings - Fork 12
jq examples and tutorial
John Bogovic edited this page May 10, 2023
·
7 revisions
arr.json
https://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]
}
}
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("_")'
jq '.one = [1,"one","i"]' obj.json
jq '.one |= [.] + ["one","i"] | .one | .[1]' obj.json
jq '.one |= [.] + ["one","i"] | .one[1]' obj.json
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 )'
jq '.[0] | map_values({decimal: .} )' obj.json
jq -s '(.[0] | map_values({decimal: .} )) * .[1]' obj.json obj_obj.json
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 .[] as $i (1; . * $i)' arr.json
jq -n 'include "fact"; 4 | fact'
jq -n 'include "fib"; [range(10)] | map(fib)'
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")'
jq '..' obj.json
jq '.one |= [.] + ["one","i"] | ..' obj.json
jq '.one |= [.] + ["one","i"] | walk( if type == "number" then . + 1 else . end)' obj.json