moodle/moodle · error · SyntaxError

JSON.parse

Error message

JSON.parse

What it means

Y.JSON.parse (the YUI JSON shim) validates text with its internal safety regex before evaluating. When the text fails validation (or the native path is unavailable and the text is not a valid JSON structure), it throws new SyntaxError('JSON.parse'), mirroring native JSON.parse's generic message. The real problem is almost always invalid or non-conforming JSON text, or an unexpected non-string input reaching the parser.

Solutions

  1. Log and inspect the exact text before parsing; fix the producer to emit valid JSON (double-quoted keys, no trailing commas/comments)
  2. Wrap Y.JSON.parse in try/catch and fall back to a safe default or surface a clear message
  3. Ensure the endpoint returns Content-Type application/json and status 200 before parsing
  4. If input may be a JS object already, parse only when typeof input === 'string'

Example fix

// before
var data = Y.JSON.parse(xhr.responseText);
// after
var data;
try {
  data = Y.JSON.parse(xhr.responseText);
} catch (e) {
  console.error('Invalid JSON:', xhr.responseText.slice(0, 200));
  data = { error: 'invalid-json' };
}
Defensive patterns

Strategy: validation

Validate before calling

function safeJsonParse(text, reviver) {
  if (typeof text !== 'string' || !/^\s*[\[\{"]/.test(text)) {
    throw new SyntaxError('safeJsonParse: input is not JSON text');
  }
  return Y.JSON.parse(text, reviver);
}

Type guard

function isJsonString(s) { return typeof s === 'string' && /^(\s*[\[{])|(\s*"(\\.|[^"\\])*")|\s*-?\d|\s*(true|false|null)\s*$/.test(s); }

Try / catch

try {
  var data = Y.JSON.parse(text);
} catch (e) {
  if (e instanceof SyntaxError) {
    console.error('Invalid JSON received:', String(text).slice(0, 200));
    data = null;
  }
}

Prevention

When it happens

Trigger: Calling Y.JSON.parse(text) where text contains non-JSON syntax: single quotes, trailing commas, unquoted or single-quoted keys, comments, unescaped control characters, undefined/NaN literals, or empty string; also when eval fallback encounters a parse error.

Common situations: Parsing server responses that are actually HTML error pages or empty bodies; hand-built JSON strings with JS-object-literal syntax; parsing 'undefined'/'null string mixups; older browsers lacking native JSON where the shim's stricter safety regex rejects texts native parsers might accept.

Understand the failure class

Background: JSON parse error: "Unexpected token" / "not valid JSON" / "failed to parse" — what JSON parsers are really complaining about — this error's family across 45 libraries.

Related errors


AI-assisted analysis of moodle/moodle@48ea8c3322 (2026-09-14). Data as JSON: /api/errors/3b865f25c01bfba5. Report an issue: GitHub.

Appendix: source

Thrown at public/lib/yuilib/3.18.1/json-parse-shim/json-parse-shim-debug.js:175

        s += '';
    }

    // Replace certain Unicode characters that are otherwise handled
    // incorrectly by some browser implementations.
    // NOTE: This modifies the input if such characters are found!
    s = s.replace(_UNICODE_EXCEPTIONS, _escapeException);

    // Test for any remaining invalid characters
    if (!_UNSAFE.test(s.replace(_ESCAPES,'@').
                        replace(_VALUES,']').
                        replace(_BRACKETS,''))) {

        // Eval the text into a JavaScript data structure, apply any
        // reviver function, and return
        return _revive(eval('(' + s + ')'), reviver);
    }

    throw new SyntaxError('JSON.parse');
};

// Property available for testing if the implementation being used
// is native or a shim
Y.JSON.parse.isShim = true;


}, '3.18.1', {"requires": ["json-parse"]});

View on GitHub (pinned to 48ea8c3322)