Learn/Working with JSON

Debugging JSON — Browser DevTools, Postman, VS Code & CLI

When an API returns unexpected data, a config file breaks your build, or a parse error appears with no helpful message — you need to debug JSON. This guide covers the tools and techniques developers actually use: Chrome DevTools, Postman, VS Code, jq, and console patterns.

The JSON Debugging Toolkit

Choose Your Debugging Tool

1. Browser DevTools (Chrome / Edge / Firefox)

Network Tab — Inspect API Responses

The Network tab is the first place to check when an API returns unexpected JSON:

  1. Open DevTools (F12 or Cmd+Option+I)
  2. Go to the Network tab
  3. Filter by Fetch/XHR to see only API calls
  4. Trigger the request (click button, refresh page)
  5. Click the request → Preview tab for collapsible tree view
  6. Click Response tab for raw JSON text
  7. Check Headers tab for Content-Type and status code

Tip

If the response is not showing as JSON in the Preview tab, check the Content-Type header. It should be application/json. If the server sends text/html, you might be getting an error page instead of JSON.

Console — Logging and Inspecting JSON

Effective console.log for JSONjavascript
1// Basic — shows collapsed object
2console.log(data);
3
4// Table view — great for arrays of objects
5console.table(data.users);
6
7// Group related logs
8console.group('API Response');
9console.log('Status:', response.status);
10console.log('Data:', data);
11console.log('User count:', data.users.length);
12console.groupEnd();
13
14// Pretty-print in console
15console.log(JSON.stringify(data, null, 2));
16
17// Copy to clipboard for pasting into a tool
18copy(JSON.stringify(data, null, 2)); // Chrome DevTools only

Sources Tab — Breakpoint on JSON.parse

To catch parse errors before they propagate:

  1. Go to Sources tab → Breakpoints panel
  2. Expand XHR/fetch Breakpoints
  3. Add a breakpoint matching your API URL pattern
  4. When the breakpoint hits, step through the response handling code
  5. Inspect the raw response text before JSON.parse()

2. Postman / Insomnia

Testing API Responses

Postman test scriptsjavascript
1// Verify response is valid JSON
2pm.test("Response is JSON", () => {
3 pm.response.to.have.header("Content-Type", /json/);
4 pm.response.to.be.json;
5});
6
7// Check specific fields
8pm.test("User has required fields", () => {
9 const user = pm.response.json();
10 pm.expect(user).to.have.property("id");
11 pm.expect(user).to.have.property("name");
12 pm.expect(user).to.have.property("email");
13 pm.expect(user.name).to.be.a("string");
14});
15
16// Validate against schema
17const schema = {
18 type: "object",
19 required: ["id", "name", "email"],
20 properties: {
21 id: { type: "number" },
22 name: { type: "string" },
23 email: { type: "string", format: "email" },
24 },
25};
26pm.test("Matches schema", () => {
27 pm.expect(pm.response.json()).to.have.jsonSchema(schema);
28});

Debugging Tips in Postman

FeatureHow to Use
Pretty viewBody tab → Pretty → auto-formats JSON
Search in responseCtrl+F in response body to find specific keys
Save as exampleSave response as an example for documentation
ConsoleView → Show Postman Console for full request/response logs
EnvironmentsStore API URLs, tokens as variables for easy switching
Collection runnerRun all requests in sequence — catch regressions

3. VS Code JSON Debugging

Built-in JSON Validation

VS Code validates .json files automatically. To enable JSON Schema validation for specific files:

.vscode/settings.jsonjson
1{
2 "json.schemas": [
3 {
4 "fileMatch": ["package.json"],
5 "url": "https://json.schemastore.org/package.json"
6 },
7 {
8 "fileMatch": ["tsconfig.json", "tsconfig.*.json"],
9 "url": "https://json.schemastore.org/tsconfig.json"
10 },
11 {
12 "fileMatch": ["src/config/*.json"],
13 "schema": {
14 "type": "object",
15 "required": ["host", "port"],
16 "properties": {
17 "host": { "type": "string" },
18 "port": { "type": "integer", "minimum": 1, "maximum": 65535 }
19 }
20 }
21 }
22 ]
23}

Useful Extensions

ExtensionWhat It Does
JSON CrackVisualize JSON as an interactive tree/graph
Paste JSON as CodeGenerate TypeScript interfaces from JSON
REST ClientSend HTTP requests from .http files, see JSON responses inline
Pretty JSONFormat/minify JSON with a keyboard shortcut
Error LensShows JSON validation errors inline next to the line

4. Command Line with jq

jq is the most powerful command-line JSON processor:

Essential jq commandsbash
1# Pretty-print
2echo '{"name":"Alice","age":30}' | jq .
3
4# Extract a field
5curl -s https://api.github.com/users/octocat | jq '.login'
6# "octocat"
7
8# Extract from nested object
9curl -s https://api.github.com/users/octocat | jq '.login, .public_repos'
10
11# Filter an array
12echo '[{"name":"Alice","active":true},{"name":"Bob","active":false}]' | jq '.[] | select(.active == true)'
13
14# Map over array — extract just names
15echo '[{"name":"Alice"},{"name":"Bob"}]' | jq '[.[] | .name]'
16# ["Alice", "Bob"]
17
18# Count array items
19echo '[1,2,3,4,5]' | jq 'length'
20# 5
21
22# Get keys of an object
23echo '{"a":1,"b":2,"c":3}' | jq 'keys'
24# ["a", "b", "c"]
25
26# Compact output (no whitespace)
27jq -c . data.json

jq with APIs

Real-world jq workflowsbash
1# List all repo names from GitHub API
2curl -s "https://api.github.com/users/octocat/repos" | jq '.[].name'
3
4# Get repos with more than 100 stars
5curl -s "https://api.github.com/users/octocat/repos" | jq '[.[] | select(.stargazers_count > 100) | {name, stars: .stargazers_count}]'
6
7# Extract specific fields and reformat
8curl -s "https://api.example.com/users" | jq '.data[] | {id, fullName: (.firstName + " " + .lastName), email}'
9
10# Save filtered output to a file
11curl -s "https://api.example.com/data" | jq '.results' > filtered.json

5. Debugging Common Scenarios

Scenario: 'Unexpected token < in JSON'

This usually means the server returned HTML (an error page) instead of JSON:

  1. Open DevTools → Network tab
  2. Find the failing request
  3. Check Response tab — if it starts with <!DOCTYPE, it's HTML
  4. Check the status code — 404 or 500 means the API endpoint is wrong or broken
  5. Check Content-Type header — should be application/json

Scenario: 'undefined is not valid JSON'

This means JSON.parse() received undefined instead of a string:

1// Common cause: response body is empty (204 No Content)
2const text = await response.text();
3console.log('Raw response:', JSON.stringify(text)); // Debug: see exactly what was received
4
5// Fix: check before parsing
6if (text) {
7 const data = JSON.parse(text);
8} else {
9 console.log('Empty response body');
10}

Scenario: JSON Has Wrong Shape

The JSON parses fine but has unexpected field names or structure:

1// Log the full structure to understand the shape
2const data = await response.json();
3console.log('Keys:', Object.keys(data));
4console.log('Type:', typeof data);
5console.log('Is array:', Array.isArray(data));
6console.log('Full structure:', JSON.stringify(data, null, 2));
7
8// Check if data is wrapped in an envelope
9// API might return { data: { users: [...] } } instead of { users: [...] }
10console.log('data.data?', data.data);

Try It — Validate Suspicious JSON

Try It Yourself

Paste suspected broken JSON here to validate it

Frequently Asked Questions

How do I see API JSON responses in Chrome DevTools?
Open DevTools (F12), go to the Network tab, make the API request, click on the request row, and select the "Response" or "Preview" tab. Preview shows a collapsible tree view of the JSON. You can also right-click the request and choose "Copy response" to paste into a JSON viewer.
What is jq and how do I use it?
jq is a command-line JSON processor. Install it via brew (macOS), apt (Linux), or choco (Windows). Basic usage: curl api.example.com | jq ".data.users[0].name" to extract a specific value. It supports filtering, mapping, sorting, and transforming JSON directly in the terminal.
How do I debug JSON parse errors?
Most parse errors include an offset or position. Use a JSON validator (online or in VS Code) to see the exact line and character. Common causes: trailing commas, single quotes, comments, unescaped characters in strings, or a response that is not JSON at all (HTML error page).
Can VS Code validate JSON automatically?
Yes. VS Code validates JSON syntax in real-time for .json files. For schema validation, add a "$schema" property pointing to a JSON Schema URL, or configure file associations in settings.json under "json.schemas". Red squiggly underlines show validation errors.
How do I debug JSON in Postman?
Send a request, then check the Body tab (select "Pretty" view). Postman auto-formats JSON responses. Use the Tests tab to write assertions: pm.test("has user", () => { pm.expect(pm.response.json().name).to.equal("Alice") }). Use the Console (View > Show Postman Console) for detailed request/response logs.