Skip to content

k6 JSON Response Parsing Error Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about k6 json response parsing error fix. We cover key concepts, practical examples, and best practices.

Your k6 script throws TypeError: Cannot read property 'name' of undefined when parsing JSON — the response body is not valid JSON, the structure is different than expected, or res.json() is called on an empty body.

The Problem

import http from 'k6/http';
import { check } from 'k6';

export default function () {
  const res = http.get('https://api.example.com/users');
  const user = res.json();
  console.log(user.data.users[0].name);
}
ERRO[0002] TypeError: Cannot read property 'users' of undefined

The JSON response does not match the expected structure. The server returned an error object with a different shape.

Step-by-Step Fix

1. Validate JSON structure before access

import http from 'k6/http';
import { check } from 'k6';

export default function () {
  const res = http.get('https://api.example.com/users');

  check(res, {
    'response is JSON': (r) => r.headers['Content-Type'].includes('json'),
    'status is 200': (r) => r.status === 200,
  });

  if (res.status !== 200) {
    console.log(`Error: ${res.body}`);
    return;
  }

  const data = res.json();
  if (data && data.users && data.users.length > 0) {
    console.log(`First user: ${data.users[0].name}`);
  }
}

2. Handle nested JSON safely

import http from 'k6/http';

export default function () {
  const res = http.get('https://api.example.com/users');
  const data = res.json();

  // Safe access with optional chaining
  const firstName = data && data.users && data.users[0] && data.users[0].name;
  console.log(`Name: ${firstName || 'unknown'}`);
}

3. Parse specific fields with tags

import http from 'k6/http';
import { check } from 'k6';

export default function () {
  const res = http.get('https://api.example.com/users');
  const data = res.json();

  data.users.forEach((user, index) => {
    check(user, {
      [`user_${index}_has_email`]: (u) => typeof u.email === 'string',
    });
    console.log(`User ${index}: ${user.name} <${user.email}>`);
  });
}

4. Handle JSON parse errors

import http from 'k6/http';

export default function () {
  const res = http.get('https://api.example.com/users');

  let data;
  try {
    data = JSON.parse(res.body);
  } catch (e) {
    console.log(`JSON parse error: ${e}`);
    data = {};
  }

  console.log(data.users ? data.users.length : 0);
}

5. Use response size as a sanity check

import http from 'k6/http';
import { check } from 'k6';

export default function () {
  const res = http.get('https://api.example.com/users');

  check(res, {
    'body is not empty': (r) => r.body.length > 0,
    'body is reasonable size': (r) => r.body.length > 100,
  });

  const data = res.json();
  console.log(`Received ${data.users.length} users`);
}

Expected output:

     ✓ response is JSON
     ✓ status is 200
     ✓ body is not empty

     First user: Alice Johnson <alice@example.com>

Prevention Tips

  • Validate Content-Type header before calling res.json()
  • Check res.status before parsing the body
  • Use safe access patterns with guards for nested objects
  • Wrap JSON parsing in try/catch for defensive coding
  • Log the raw body when parsing fails for debugging

Common Mistakes with json response

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world K6 code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does res.json() sometimes fail silently?

res.json() returns null for non-JSON responses. Always check the Content-Type or use typeof res.json() === 'object' to validate before accessing properties. A failed parse returns null without throwing an error.

Can I parse large JSON responses efficiently?

For large responses, consider using res.body directly with substring checks or regex instead of full JSON parsing. If you need structured data, parse only what you need and avoid storing the full parsed object across iterations.

How do I handle paginated JSON responses?

Collect results across multiple requests: call the API with incrementing page parameters, JSON.parse() each response, and aggregate the data. Use __ITER or __VU to track pagination state across iterations.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro