Urgent.News

What's breaking now, across hundreds of outlets.

Tech

jq Tutorial: Slice JSON Like a Pro From the Terminal

Quick answer jq is a small command-line tool that reads JSON, filters it, reshapes it, and prints the result, all without writing a script. It is not jQuery, the old browser library; the two share two letters and nothing else. You call an API and get back a wall of JSON. Somewhere in it is the one number you need, maybe total sales for Karachi, but the response is five hundred lines long. A…

jq is a command-line tool that works with JSON data, allowing you to filter, reshape, and print the results without writing a script. It reads JSON from files or pipes, applies a filter expression, and prints only the requested data. The tool is built specifically for JSON, so it cannot handle other data formats like YAML, CSV, or XML.

Before using jq, verify three things: what jq is, the learning curve, and the source of the JSON data. The basics of jq, such as dot access, pipes, select, and map, take only an afternoon to learn. However, more advanced features like group_by and reduce can take longer to master. Error messages may be brief, but a long one-liner is difficult to review. jq works well with API responses piped from curl or log files containing JSON lines. It cannot edit data in place, as it prints a new document each time and never touches the file.

In this example, a small shop in Karachi has five orders recorded in orders.json. The first part of the analysis counts the orders and lists the Karachi customers. The command 'jq 'length' orders.json' returns 5, indicating there are five orders in the file. The command 'jq -r '.[] | select(.city == "Karachi") | .customer' orders.json' lists the Karachi customers: Sana, Hamza, and Ayesha.

The second part of the analysis adds up the total sales. The command 'jq '[.[] | .total] | add' orders.json' returns an error because one total is a string, not a number. To fix this, use 'jq '[.[] | .total | tonumber] | add' orders.json', which correctly returns the grand total of Rs 45,350. The same fix can be used to calculate sales per city, sorting the data by city first.

Rewritten by urgent.news; may contain errors — check the original.

Source: dev.to

Read the original at dev.to →

Report a problem with this story

More in Tech

The First Commands to Run When a GBase 8a Cluster Slows Down

When a healthy GBase 8a cluster suddenly develops intermittent problems, the hardest part is usually finding where the fault sits. Here are the commands I reach for first.

  • Examine cluster state with gcadmin command, noting CLOSE and OFFLINE states
  • Identify longest-running SQL queries at coordinator layer, check time column
  • Check OS errors, resource saturation, swap usage on identified problematic node

More from Tuesday 24 November →