Format JSON in Bash and curl output

How to pretty-print JSON from curl in Bash with jq or Python, what formatting changes and what it doesn't, and when to keep the raw response instead.

curl prints a response body exactly as the server sent it, and many APIs send compact JSON on a single line. To make that output readable in a terminal, you pipe it through a JSON-aware formatter that adds line breaks and indentation. This review covers what that step does, what it can quietly alter, and when you should keep the raw output.

Recommendation

For reading API responses while developing or debugging, piping curl into jq is the most practical default. If jq is not installed, Python's built-in json.tool module does the same job. The main benefit goes beyond looks. Both tools parse the input before printing it, so a successful run also confirms the response is syntactically valid JSON. The tradeoff that matters most is that neither tool reformats the original text in place. Each one parses the document and writes out new text. The result is equivalent JSON, but it is not byte-for-byte the same as what the server sent.

Keep the raw, unformatted response in these situations:

  • You need to verify a signature, checksum or hash computed over the exact response bytes.
  • You are recording evidence of what a server returned, such as for a bug report or audit trail.
  • The payload contains very large integers or high-precision decimals, and you have not confirmed that your formatter preserves them.
  • A downstream tool or log pipeline expects one JSON document per line.
  • The response may not be JSON at all, for example an HTML error page or a plain-text message, and you need to see it unchanged.

Basic commands

In the examples below, API_URL is a placeholder for your endpoint. The -sS flags turn off curl's progress meter but still show error messages. Plain -s hides both.

# Pretty-print with jq (2-space indent by default)
curl -sS "$API_URL" | jq .

# Pretty-print with Python's standard library (4-space indent by default)
curl -sS "$API_URL" | python3 -m json.tool

# jq variations
curl -sS "$API_URL" | jq --indent 4 .   # wider indentation
curl -sS "$API_URL" | jq --tab .        # tabs instead of spaces
curl -sS "$API_URL" | jq -S .           # sort object keys
curl -sS "$API_URL" | jq -c .           # compact, one line
curl -sS "$API_URL" | jq -M .           # no color

# Format a saved file
jq . response.json > response.pretty.json

curl's --json option is easy to mistake for a formatting option. It is not. It sends a JSON request body and sets the matching request headers, but it leaves the response output unformatted. Also keep curl's -i flag out of a pipe into a formatter. That flag puts HTTP headers in front of the body, so the formatter receives text that is not JSON and fails to parse it. If you need the headers, write them to a separate file with -D, for example -D headers.txt.

Avoid hand-rolled formatting with sed, awk or tr. Those tools have no concept of JSON strings. A comma or brace inside a quoted value looks the same to them as a structural one, so they can break the data while appearing to work.

What formatting actually changes

In this context, "formatting" means changing the whitespace between JSON tokens. Spaces, tabs and newlines outside of strings carry no meaning in JSON, so adding them leaves the data the same. Values inside strings keep their content. Nothing is reversed or mirrored, and no characters are swapped for styled Unicode look-alikes. The colors jq shows in a terminal are a display effect only. They come from terminal escape codes and are not part of the data.

Here is a compact input followed by jq's default output:

{"id":1,"tags":["a","b"],"name":"Zoë"}
{
  "id": 1,
  "tags": [
    "a",
    "b"
  ],
  "name": "Zoë"
}

Python's json.tool prints the same structure with four-space indentation. By default it escapes non-ASCII characters, so the last line comes out as "name": "Zo\u00eb". In JSON this means the same thing, but it is harder for a person to read. Adding --no-ensure-ascii keeps the original characters.

Re-serializing the document can also change more than whitespace:

Effect | jq | python3 -m json.tool
Key order | Kept as in input unless -S is used | Kept as in input unless --sort-keys is used
Non-ASCII text | Written as UTF-8 by default; -a escapes it | Escaped as \uXXXX by default; --no-ensure-ascii keeps it
Duplicate keys in one object | Collapsed; the last value is kept | Collapsed; the last value is kept
Large integers | Some versions store numbers as double-precision floats, which can alter very large values; newer releases keep the original number when it is not modified | Integers are kept exactly
High-precision decimals | Same caveat as large integers | Parsed as floats, so extra precision can be rounded off
Non-standard values such as NaN | Depends on version | Accepted by default, so the check is looser than strict JSON

Two rows in that table involve real data changes. When duplicate keys collapse, information is lost without any warning. Precision loss in numbers changes the values themselves. If either one matters for your payload, check the formatted output against the raw response. Run jq --version to find out which jq behavior applies on your system.

Using the formatter as a validator in scripts

Both tools exit with a non-zero status when the input is not valid JSON, so a script can use them as a check. In a pipeline, though, Bash by default reports only the exit status of the last command. A failed curl request can therefore look like a success. Turn on pipefail so that a failure at any stage is reported.

set -o pipefail

# Validate without printing anything
if curl -sS "$API_URL" | jq empty; then
  echo "valid JSON"
else
  echo "request failed or response is not valid JSON" >&2
fi

Since json.tool accepts NaN and Infinity by default, jq is the better choice when you need a strict check. A pass from either tool means only that the syntax is valid. It does not check that the response has the fields or types your code expects.

Copying, sharing and accessibility

  • Color codes: jq turns color off automatically when output goes to a file or a pipe instead of a terminal. If you force color with -C and redirect the output, the escape codes are written into the file and it is no longer valid JSON. Use -M, or the default, when saving output.
  • Copying from a terminal: what gets copied depends on the terminal. Usually it is the visible text, without color codes. Check what lands on your clipboard before relying on it.
  • Pasting into other tools: chat apps, ticket systems and rich-text editors may collapse whitespace, swap straight quotes for curly ones, or convert tabs. Pasting inside a code block where the destination supports one, or attaching a .json file, avoids most of this. Results vary by destination and have not been tested here.
  • One line or many: indented output is easier to scan, but it breaks tools that expect one JSON record per line. Use jq -c when output feeds into logs or line-based processing.
  • Screen readers and color: color only reinforces structure, so turning it off with -M loses no information. How screen readers announce deeply indented JSON varies by tool and settings. No documentation or test covering this was available for this review.
  • Right-to-left text: strings with right-to-left scripts such as Arabic or Hebrew may appear in a different visual order in a terminal. The stored characters are unchanged; only how the terminal displays them differs.

If the exact response may matter later, save it before formatting, for example with curl -sS -o response.json, and format a copy. That way you keep the original bytes and still have a readable version.

Evidence gaps

The behavior described here is the documented default behavior of jq, Python's json module and curl. No version-by-version testing, terminal or clipboard testing, assistive-technology testing, or performance measurements on large responses were available. Defaults and options differ across releases, especially for jq's number handling. Check against the version installed on your system before relying on any one detail.