Process and Highlight JSON with jq

Once you know enough command-line basics, 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 command-line tool

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.

Python-based alternatives

Using Python’s JSON library

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
}

Advanced JSON queries in Python

If you are looking for advanced ways to query JSON from within Python, head over to our page on queries JSON in Python with JmesPath.

Get certified with our courses

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

Related articles

Leave a Comment

Python Newsletter

Before you leave, you may want to sign up for my newsletter.

Tips & Tricks
News
Course discounts

Googler exit intent popup

No spam & you can unsubscribe at any time.