Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Operations 6 min read

Master JSON Formatting on the Command Line with jq: Tips and Real-World Examples

This guide shows how to use the jq command‑line tool to elegantly format, query, and extract data from JSON responses across Linux, Windows, and macOS, providing practical examples, syntax basics, and integration with curl for API testing.

In everyday development work, most API responses are in JSON format, which can be both helpful and cumbersome to read. The article introduces a practical way to handle JSON using the versatile command‑line utility jq, which runs on Linux, Windows, and macOS.

jq Basic Syntax

JSON data can be piped into jq via standard input. For example:

echo '{"name":"FunTester"}' | jq
{
  "name": "FunTester"
}

Without any arguments, jq simply pretty‑prints the input JSON. The most basic filter is ., which returns the entire JSON document, similar to JsonPath.

Accessing Object Fields and Arrays

Given a sample file FunTester.json:

{
    "name": "FunTester",
    "article": [
        {"author": "tester1", "title": "ApiTest"},
        {"author": "tester2", "title": "performanceTest"}
    ]
}

Retrieve the name field:

cat FunTester.json | jq '.name'
"FunTester"

Extract an array element:

cat FunTester.json | jq '.article[1]'
{
  "author": "tester2",
  "title": "performanceTest"
}

Combine filters to get a nested value:

cat FunTester.json | jq '.article[1].title'
"performanceTest"

List a specific key from all array objects:

cat FunTester.json | jq '.article[].title'
"ApiTest"
"performanceTest"

Processing API Responses with jq

The article demonstrates using jq together with a mock API server (built with the moco framework) that returns the same FunTester.json content. After confirming the endpoint http://localhost:12345/jq/test serves the JSON, the following curl‑jq pipeline extracts multiple fields:

curl http://localhost:12345/jq/test | jq '.name,.article[1].author'
"FunTester"
"tester2"

Multiple filters are separated by commas, allowing simultaneous extraction of different values. Compared with JsonPath tools, jq offers a concise, command‑line‑friendly syntax and clean output formatting.

Further Exploration

The author notes that more advanced jq functions and filters will be explored in future posts, encouraging readers to apply the demonstrated techniques to their own JSON handling tasks.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

data processingJSONLinuxshellCommand LinejqWindowsmacOS

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion