How to read and debug JSON API responses
The checkout page shows “৳NaN”, the app crashes with “Unexpected token <”, or a list is simply empty. Nine times out of ten the bug is not in your code but in a wrong assumption about what the API actually sent. The fastest way to debug is to stop guessing and look at the raw response: its status code, its headers and its body. This guide shows how to do that with the browser, curl and Postman, how to point at exactly the value you need, and which API habits cause the most trouble.
1. Inspect it in the browser’s DevTools
For anything your web page requests, the browser already has the full answer.
- Press F12 (or Ctrl+Shift+I) and open the Network tab.
- Click the Fetch/XHR filter so you only see API calls, then reload the page or repeat the action.
- Click a request. Headers shows the URL, method, status code and
Content-Type; Preview shows the JSON as a collapsible tree; Response shows the raw text exactly as received.
Two features save a lot of time. Preserve log keeps requests when the page redirects. And right-clicking a request gives Copy → Copy as cURL, which reproduces the exact request — headers, cookies and body — in a terminal.
Careful when sharing: a copied cURL command contains your cookies and Authorization token. Remove them before pasting it into a chat or a bug report.
2. Use curl in the terminal
curl ships with Linux, macOS and current Windows 10/11. The flags you need most:
# -i: show the status line and response headers above the body
curl -i https://api.example.com/v1/products?page=1
# -s: silent (no progress bar), so the output can be piped to a formatter
curl -s https://api.example.com/v1/products | python -m json.tool
# with jq you can also pick out one value
curl -s https://api.example.com/v1/products | jq '.data.items[0].price'
# send JSON and a token
curl -s -X POST https://api.example.com/v1/orders \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
--data @order.json
On Windows PowerShell 5.1, curl is an alias for Invoke-WebRequest, so type curl.exe to get the real curl. Putting the request body in a file with --data @order.json also avoids painful quote escaping in Windows shells.
3. Use Postman (or a similar client)
Postman, Insomnia, Bruno and VS Code REST extensions are handy when you call the same endpoints repeatedly. They show the status, time and size next to the body; the Pretty view formats JSON, and the headers are in a separate tab. Save requests in a collection, keep tokens in environment variables rather than in the URL, and paste a cURL command from DevTools to import a request in one step.
4. Read the status and Content-Type first
Before you look at the body, check these two things. They tell you whether the body is what you expect at all.
| Status | Meaning | What the body usually is |
|---|---|---|
| 200, 201 | Success / created | The data you asked for |
| 204 | Success, no content | Empty — calling JSON.parse("") throws |
| 400, 422 | Your input was rejected | A JSON error object; read it, it usually names the field |
| 401, 403 | Not logged in / not allowed | JSON error, or an HTML login page |
| 404 | Wrong URL or missing record | Often an HTML page from the web server |
| 429 | Too many requests | Check the Retry-After header |
| 500, 502, 503, 504 | Server or gateway failure | Frequently HTML from a proxy or load balancer |
The Content-Type header should be application/json (possibly with ; charset=utf-8). If it is text/html, parsing will fail no matter what. A defensive fetch helper checks both before parsing:
async function getJson(url, options = {}) {
const res = await fetch(url, { ...options, headers: { Accept: 'application/json', ...options.headers } });
const type = res.headers.get('content-type') || '';
const text = await res.text();
if (!type.includes('application/json')) {
throw new Error(`Expected JSON but got ${res.status} ${type}: ${text.slice(0, 120)}`);
}
const body = text ? JSON.parse(text) : null;
if (!res.ok) {
throw new Error(`API error ${res.status}: ${JSON.stringify(body)}`);
}
return body;
}
Reading the body as text first means that when something goes wrong, your error message contains the start of what the server actually sent — usually enough to see the problem immediately.
5. Point at the exact value with a JSON path
Large responses are easier to talk about with a path. The common notation starts with $ for the root, uses dots for keys and brackets for array positions (starting at 0):
{
"data": {
"items": [
{ "id": 501, "name": "Rice 5kg", "price": 420 },
{ "id": 502, "name": "Lentils 1kg", "price": 145 }
]
}
}
$.data.items[0].price → 420
$.data.items[1].name → "Lentils 1kg"
The same path works almost unchanged in code: body.data.items[0].price in JavaScript, body["data"]["items"][0]["price"] in Python, or .data.items[0].price in jq. Keys with spaces or hyphens need brackets: $["order-id"]. In JavaScript, optional chaining (body.data?.items?.[0]?.price) avoids a crash when part of the path is missing.
Tip: in the formatter’s Tree view, click any key and the path bar shows its full path, ready to copy into a bug report or your code.
6. Recognise envelopes and pagination
Few APIs return a bare list. Most wrap the data in an envelope with metadata, and split long lists into pages. Two common shapes:
// Page numbers
{ "data": [ ... ], "meta": { "page": 2, "per_page": 20, "total": 134 } }
// Cursor
{ "data": [ ... ], "next_cursor": "eyJpZCI6NTIwfQ" }
With cursors you keep requesting until the cursor is empty:
async function fetchAll(baseUrl) {
const all = [];
let cursor = null;
do {
const url = cursor ? `${baseUrl}?cursor=${encodeURIComponent(cursor)}` : baseUrl;
const page = await getJson(url);
all.push(...page.data);
cursor = page.next_cursor;
} while (cursor);
return all;
}
If a list looks “randomly” short, check for meta.total or a next link — you are probably looking at page one.
7. Common API mistakes to watch for
- HTML error pages. “Unexpected token <” means the body starts with
<!DOCTYPE html>. Check the status and URL; a proxy or a login redirect answered instead of the API. - Numbers as strings. If
"total": "1250.50"is a string, thentotal + 50gives"1250.5050"in JavaScript. Convert explicitly, and for money prefer integer poisha/cents or a decimal library. - null vs missing.
"discount": nulland nodiscountkey at all may mean different things. In JavaScript both read as “nothing” with== null, but"discount" in bodytells them apart. - Big integers losing precision. JavaScript numbers are exact only up to
9007199254740991.JSON.parse('{"id": 1234567890123456789}')gives1234567890123456800— a different ID. Ask the API to send such IDs as strings (many do, e.g. anid_strfield). Python’sjsonmodule keeps them exact. - Inconsistent date formats. Epoch seconds, epoch milliseconds,
"2026-09-27T10:30:00Z"and"27/09/2026"can appear in the same API.new Date("27/09/2026")is an Invalid Date. Prefer ISO 8601 with a time zone, and check whether a timestamp has 10 digits (seconds) or 13 (milliseconds).
FAQ
Why do I get a CORS error when the same URL works in curl?
CORS is enforced only by browsers. The server must send headers such as Access-Control-Allow-Origin for your site. curl and Postman ignore CORS, so the fix belongs on the server (or a backend proxy), not in your fetch call.
Preview shows data but my code gets undefined. Why?
Usually the path is one level off — the data is inside an envelope such as body.data, or you forgot to await res.json(). Copy the exact path from a tree view and compare.
How do I handle IDs larger than 253 in JavaScript?
Best: have the API send them as strings. If you can’t, newer runtimes (including current Node.js and Chrome) pass the original text to a JSON.parse reviver as context.source, which you can turn into a BigInt; check browser support before relying on it.