Command line json

Sometimes you have JSON that you want to quickly check from the command line. Although you could write something quick in Python or your language of choice, maybe you want the bare minimum of setup.

Sample JSON

For the rest of this page, we will use a small JSON sample from Mockaroo. Here is some sample data:

[{"id":1,"org":{"name":"Kare"},"people":["Trudy Feldharker"]},
{"id":2,"org":{"name":"Zoombeat"},"people":["Eduard Bertram"]},
{"id":3,"org":{"name":"Tazz"},"people":["Gregor Le Friec","Creight Tubritt","Nester Cranch"]}]

Note the lack of any helpful spacing. If you want to space it out, you can use Python to reformat it (see post: Reading Json).

Bash only

If you want the bare minimum, along with tools that are probably already installed, you can use Python and grep.

For example, if you want org name only, try this:

python -m json.tool sample.json | grep name
            "name": "Kare"
            "name": "Zoombeat"
            "name": "Tazz"

This works for a very quick approximation. But what if we want only the peoples’ names, and not the company name? In this case, there is nothing we can grep for.

Just a bit more

Using jq, you can find peoples names! Note: you may first need to install it. Here’s an example:

 jq '.[].people[]' sample.json
"Trudy Feldharker"
"Eduard Bertram"
"Gregor Le Friec"
"Creight Tubritt"
"Nester Cranch"

You may want the names without any quotes. For this you can use the -r option:

jq -r '.[].people[]' sample.json
Trudy Feldharker
Eduard Bertram
Gregor Le Friec
Creight Tubritt
Nester Cranch

The jq query syntax can be cryptic. However the more you use it, the less intimidating it becomes. Knowing how to use this tool will help you quickly understand or reformat any JSON you encounter.