Process JSON with jq

I think we’ve played around enough. It’s time to actually learn some useful stuff that you can apply in your daily work! Since JSON is super ubiquitous, I’d like to teach you some useful command-line JSON processing voodoo first.

The jq tool is usually not installed by default. If you don’t have it, please install it for your operating system. If you’re on MacOS, you might want to look into Homebrew.

A very basic example of jq usage is this:

echo '{ "Price": 10.0, "Name": "Cable" }' | jq

The result is a well-formatted, colorized version of the JSON you feed it:

Colorizing JSON with jq
Colorizing JSON with jq

I actually use it a lot for this purpose. If you just want to view the content of a JSON file, a simple cat filename.json | jq will instantly help you out. But jq can do so much more --- it’s a full-fledged command-line JSON processor.

Say, for example, that you are only interested in the price field. You can simply obtain the price with the following command:

echo '{ "Price": 10.0, "Name": "Cable" }' | jq ".Price"

Try it! The result should be 10. This is still just touching the very basics. Just remember that jq exists and that you can get pretty much anything from your JSON files with it. Read the man page or use a search engine to find more advanced examples.

Using Python Library json.tool

Python's JSON library can also be used from the command-line, to validate and pretty-print your JSON:

$ echo "{ \"name\": \"Monty\", \"age\": 45 }" | \
python3 -m json.tool
{
    "name": "Monty",
    "age": 45
}


If you liked this page, please share it with a fellow learner: