Exploring the tool ./jq

Stefan Alfbo - May 21 - - Dev Community

I listened to this podcast today, Kodsnack 585 (in Swedish), which discuss the tool jq. The tool has been on my radar for a while, and this episode made me finally to give it a try.

The jq tool is available from the Ubuntu repository and can be installed like this.

sudo apt-get install jq
Enter fullscreen mode Exit fullscreen mode

We are going to use this JSON example from json.org to try out some things with jq, cat data.json, note that the formatting of the file is not perfect on purpose:

{"widget": {
"debug": "on",
"window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
"width": 500,
"height": 500},
    "image": {"src": "Images/Sun.png",
        "name": "sun1",
 "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
 "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}}}
Enter fullscreen mode Exit fullscreen mode

First jq command will be to pretty print the JSON, jq . data.json

pretty print

And to extract a field from the JSON data, you can use this command, jq '.widget.window.title' data.json.

extract field

We can remove a field by using the command, jq 'map(del(.text))' data.json.

remove field

It's possible to list all fields in the file, jq '[.. | objects | keys[]] | unique' data.json.

list all fields

This list can go on forever, the jq tool has many features to explore and I have only scratched a little bit of the surface here. A good starting point to learn more seems to be the Wiki at jq's GitHub repository. The show notes from the podcast Kodsnack has some excellent resources too.

However, now I have the tool on my machine and I can keep trying it out whenever I need to transform or query JSON data.

Happy querying!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .