grafana/k6 · error
unmarshalling response body to JSON
Error message
unmarshalling response body to JSON: %w
What it means
Wrap of json.Unmarshal in Response.JSON: the response body bytes were fetched successfully, but they are not valid JSON (trailing data, HTML error page, BOM, or empty body). The wrapped error pinpoints the JSON syntax problem at its exact offset; results are cached, so only the first JSON() call pays the parse cost and only malformed bodies ever trigger this error.
Solutions
- Inspect response.text() to see what the server actually returned
- Guard with response.ok/status checks before parsing as JSON
- Handle non-JSON content types (HTML/XML) with text() instead of json()
Defensive patterns
Strategy: try-catch
When it happens
Trigger: Thrown at internal/js/modules/k6/browser/common/http.go:770 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of grafana/k6@8d06114777 (2026-08-18).
Data as JSON: /api/errors/ba1a9f4dfce9a6d0.
Report an issue: GitHub.
Appendix: source
Thrown at internal/js/modules/k6/browser/common/http.go:769
r.extraHeadersMu.RUnlock()
return headers
}
// JSON returns the response body as JSON data.
func (r *Response) JSON() (any, error) {
if r.cachedJSON != nil {
return r.cachedJSON, nil
}
if err := r.fetchBody(); err != nil {
return nil, fmt.Errorf("getting response body: %w", err)
}
r.bodyMu.RLock()
defer r.bodyMu.RUnlock()
var v any
if err := json.Unmarshal(r.body, &v); err != nil {
return nil, fmt.Errorf("unmarshalling response body to JSON: %w", err)
}
r.cachedJSON = v
return v, nil
}
// Ok returns true if status code of response if considered ok, otherwise returns false.
func (r *Response) Ok() bool {
if r.status == 0 || (r.status >= 200 && r.status <= 299) {
return true
}
return false
}
// Request returns the request that led to this response.
func (r *Response) Request() *Request {
return r.request
}View on GitHub (pinned to 8d06114777)