LinuxCommandLibrary
GitHub F-Droid Google Play Store

JSON

Getting Started

jq is the standard command-line JSON processor: it reads JSON from a file or stdin, applies a filter, and prints the result. The simplest filter, ., just pretty-prints.
$ jq "." file.json
copy
$ curl -s https://api.github.com/users/torvalds | jq "."
copy
$ echo '{"name": "Linux"}' | jq "."
copy
Alternatives with their own strengths: jaq (faster jq clone), dasel (also speaks YAML, TOML, XML), fx and jless (interactive viewers), gron (makes JSON greppable), jo (creates JSON), jc (converts classic command output to JSON).

Selecting Values

Filters address values by path: .key for object fields, [0] for array indexes, [] to iterate over all elements. -r prints strings raw, without quotes.
$ echo '{"name": "Linux"}' | jq ".name"
copy
$ jq ".user.address.city" file.json
copy
$ jq ".items[0]" file.json
copy
$ jq -r ".items[].name" file.json
copy
The same selection in other tools:
$ echo '{"name": "Linux"}' | dasel -r json '.name'
copy
$ echo '{"name": "Linux"}' | fx .name
copy
$ echo '{"name": "Linux"}' | jshon -e name
copy

Filtering & Transforming

jq filters chain with | just like shell pipes. select() keeps matching elements, map() transforms each one.
$ jq '.items[] | select(.price > 10)' file.json
copy
$ jq '.items | map(.name)' file.json
copy
$ jq '.items | length' file.json
copy
$ jq 'keys' file.json
copy
$ jq '.items | sort_by(.price)' file.json
copy
Build new objects from existing fields.
$ jq '.items[] | {title: .name, cost: .price}' file.json
copy

Modifying

Set or add a field with =, remove one with del(). jq never edits in place; redirect the output to a new file.
$ echo '{"name": "Linux"}' | jq '.year = 1991'
copy
$ echo '{"name": "Linux", "year": 1991}' | jq 'del(.year)'
copy
$ echo '{"name": "Linux"}' | dasel put string -r json '.year' '1991'
copy
$ echo '{"name": "Linux", "year": 1991}' | dasel delete -r json '.year'
copy

Creating

jo builds JSON from shell arguments; jq -n builds it from a filter alone.
$ jo -p name=Linux year=1991
copy
$ jq -n '{name: "Linux", year: 1991}'
copy

Grepping & Exploring

gron flattens JSON into discrete assignments so you can use plain grep, then reassembles it with -u. jless and fx browse large documents interactively with folding and search.
$ gron file.json | grep "name"
copy
$ gron file.json | grep "name" | gron -u
copy
$ jless file.json
copy
$ fx file.json
copy

Converting

yq applies jq-style filters to YAML, and dasel converts between formats. jc turns the output of classic commands into JSON so you can process it with jq.
$ yq ".name" config.yaml
copy
$ dasel -r json -w yaml < file.json
copy
$ jc ifconfig | jq ".[0].ipv4_addr"
copy
Compact output for machines: jq -c prints one line per document, useful for JSON Lines streams.
Copied to clipboard
Kai

AltStyle によって変換されたページ (->オリジナル) /