k6 JSON Response Parsing Error Fix
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-Typeheader before callingres.json() - Check
res.statusbefore 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
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro