Skip to main content

Parsing JSON Responses

Extract data from JSON responses using r.json():
import http from "k6/http";
import { check } from "k6";

export default function() {
    let res = http.get("http://httpbin.org/json");
    
    // Parse JSON response
    let data = res.json();
    
    // Access nested properties
    console.log(data.slideshow.title);
}

Extracting Values for Subsequent Requests

Correlate data between multiple requests:
1

Make initial request

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

export default function() {
    // First request to get a token or ID
    let res = http.post("http://httpbin.org/post", 
      JSON.stringify({ username: "user" }), 
      { headers: { "Content-Type": "application/json" }}
    );
    
    // Extract data from response
    let data = res.json();
    let sessionId = data.json.username;
}
2

Use extracted data

// Use extracted data in subsequent request
let res2 = http.get(`http://httpbin.org/get?session=${sessionId}`);

check(res2, {
    "status is 200": (r) => r.status === 200,
    "has session": (r) => r.json().args.session === sessionId
});

Complete Example

import http from "k6/http";
import { check, group } from "k6";

export default function() {
    group("Login and Browse", function() {
        // Step 1: Login
        let loginRes = http.post("https://api.example.com/login", 
            JSON.stringify({
                username: "testuser",
                password: "testpass"
            }),
            { headers: { "Content-Type": "application/json" }}
        );
        
        check(loginRes, {
            "login successful": (r) => r.status === 200
        });
        
        // Extract auth token
        let authToken = loginRes.json("token");
        
        // Step 2: Use token in authenticated request
        let profileRes = http.get("https://api.example.com/profile", {
            headers: {
                "Authorization": `Bearer ${authToken}`
            }
        });
        
        check(profileRes, {
            "profile retrieved": (r) => r.status === 200
        });
        
        // Extract user ID from profile
        let userId = profileRes.json("id");
        
        // Step 3: Use user ID in another request
        let ordersRes = http.get(`https://api.example.com/users/${userId}/orders`, {
            headers: {
                "Authorization": `Bearer ${authToken}`
            }
        });
        
        check(ordersRes, {
            "orders retrieved": (r) => r.status === 200,
            "has orders array": (r) => Array.isArray(r.json("orders"))
        });
    });
}

Using Regular Expressions

Extract values from HTML or text responses:
import http from "k6/http";
import { check } from "k6";

export default function() {
    let res = http.get("https://example.com");
    
    // Extract CSRF token from HTML
    let csrfMatch = res.body.match(/name="csrf_token" value="([^"]+)"/);
    let csrfToken = csrfMatch ? csrfMatch[1] : null;
    
    if (csrfToken) {
        // Use CSRF token in form submission
        let submitRes = http.post("https://example.com/submit", {
            csrf_token: csrfToken,
            data: "value"
        });
        
        check(submitRes, {
            "submission successful": (r) => r.status === 200
        });
    }
}
Data correlation is essential for realistic load tests that simulate multi-step user journeys.

Build docs developers (and LLMs) love