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:
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.