jq is a command line json parser.
Data in jq is represented as streams of JSON values.
jq .["foo$"] # The full qualified name
jq '.foo' # Short name
.foo|.bar (.foo.bar is equivalent)
jq '.foo?'
Arrays are zero-based
.[1] # returns the second element.
.[10:15]
.[]?
jq '. as $alias | $alias '
Map(x) will run the input filter x for each element of the input array, and return the outputs in a new array
Example: The Map function returns the value of Json objects array in an array
[
{"name":"JSON", "good":true},
{"name":"XML", "good":false}
]
jq 'map(.name)' input.json
[
"JSON",
"XML"
]
The transformation below is equivalent to the
declare -A name=( [key1]=value1 [key2]=value2 … )
Note that the -r is fucking important.
eval "declare -A data=($(echo '{
"total_count": "203",
"bundle_count": "10"
}' | jq -r '. | to_entries | .[] | @sh "[\(.key)]=\(.value)"'))"
echo ${data[total_count]}
echo ${data[bundle_count]}
[
{"name":"JSON", "good":true},
{"name":"XML", "good":false}
]
jq '.[] | .name, .good' input.json
"JSON"
true
"XML"
false
The | operator combines two filters by feeding the output(s) of the one on the left into the input of the one on the right.
[
{"name":"JSON", "good":true},
{"name":"XML", "good":false}
]
jq '.[] | .name' input.json
"JSON"
"XML"
From an array
[
"1",
"2"
]
join (",")
"1,2"
jq '(. + 2) * 5'
input: 1 output 15
Keys Returns:
keys
cat myJson.json | jq '."foo" | to_entries[] | .key
[
{ key1:Hello;key2:Nico },
{ key1:Hello;key2:Moi }
]
jq 'map(keys) | add | unique' input.json
[
key1,
key2
]
jq -r # To get the result as a raw string
The -r is fucking imporant.
jq -r ".Accounts[].Id | @sh"
# or
jq -r '.SITE_DATA | to_entries | .[] | .key + "=" + (.value | @sh)'
Don't forget the -r options
[
{"name":"JSON", "good":true},
{"name":"XML", "good":false}
]
jq -r '.[] | [.name, .good] | @csv' input.json
"JSON",true
"XML",false
jq -r '(map(keys) | add | unique) as $cols | map(. as $row | $cols | map($row[.])) as $rows | $cols, $rows[] | @csv'
See https://stackoverflow.com/questions/32960857/how-to-convert-arbirtrary-simple-json-to-csv-using-jq