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.

Please share this article with others!

Python Courses

Are you enjoying this free tutorial? Please also have a look at my premium courses. They offer a superior user experience with small, easy-to-digest lessons and topics, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

The Python Fundamentals Course For Beginners
Now for $29 (from $59)

Python Fundamentals I is a course for beginners that will get you started with Python in no time. Learn all the essentials, test your progress with quizzes and assignments, and bring it all together with the final course project!

Python Course for Beginners

Modules, Packages, And Virtual Environments
Now for $29 (from $59)

Python Fundamentals II covers creating your own modules and packages, using virtual environments and Python package managers to make your life as a programmer easier. Advance your productivity as a Python programmer!

Python Fundamentals 2

Leave a Comment

Share to...