This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.
Last Updated: 2024-11-21
$ jq
is an instant classic unix command and likely here to stay. Some snippets:
$ jq . my.json
$ jq .data file.json
or with optional (in this case) quotes
$ jq ".data" file.json
$ jq ".data,.name" file.json
jq '{program,message}'
- note lack of dot
Place []
at the end of the key
jq .results[]
# 0th item off the .results key
jq '.results | .[0]'
$ jq .data.product_id.value file.json
or with piping (i.e. piping and dots can substitute for one another)
$ jq ".data | .product_id | .value" file.json
.name
value for each item in a (top-level here) array$ jq ".[] | .name" file.json
(outputs an array of names)
make sure you don't forget to include any intermediate object keys
e.g.
$ jq ".[] | .intermediate.name" file.json
jq '.devDependencies + .dependencies' package.json
# Just pipe to length
$ jq '.dependencies, .devDependencies | length' package.json
16
15
$ jq '.[] | select (.coreTransactionData.productId == null)' file.json
notice use of select (conditional)
(not null is just !=
instead)
Use parenteses and the plus operator
jq '(.program + ":::" + .message)'
jq '.properties | keys' file.json
Note that 'keys' has no dot in front of it (since it is a built-in command rather than a property of this particular piece of JSON)
Transform a command like so:
jq '.[] | select ((.payload.coreTransactionData.productId != null))' paymentConfirmedEvents--FromDeals.json
into this: (i.e. wrap the entire command in the array notation, and the do the piping within this array.)
$ jq '[.[] | select ((.payload.coreTransactionData.productId != null))]' paymentConfirmedEvents--FromDeals.json
Imagine the data had keys "schema:name" (i.e. with colons in them)
# This fails
json | jq '.schema:name'
However, wrapping in square brackets and strings works:
json | jq '.["schema:name"]'
Use max
to get last item in array. If it fails, ignore error with ?
. Use the alternative operator //
to fall back
to .
which (I THINK) is a no-op here.
cat ../transparenzportal-hamburg/freeformatter-out.json| jq '.events.Event[] | .eventDates.EventDate | (max? // .) .date'
Say if you want "jack"
to just be jack
. Do this (-r
stands for raw-output
)
jq -r '.name'