JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 50 of the JSON data

JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 50 of the JSON data

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

JSON.parse: unexpected non-whitespace character after JSON data

When JSON.parse throws an error like unexpected non-whitespace character after JSON data, the issue usually isn't a bug in JavaScript's parser itself, but rather malformed data coming from your backend. The specific message at line 1 column 50 is a dead giveaway: the parser read valid JSON up to that point, hit a delimiter it couldn't interpret as part of the current structure, and immediately failed because it expected whitespace or the end of the string.

In the scenario described by developers encountering this error, the root cause is almost always accidental concatenation of multiple JSON objects without proper delimiters. The raw data provided in your PHP script output looks like this:

{"results":[{"oldID":5,"oldMain":"News papers"}]}{"results":[{"oldID":3,"oldMain":"Construction"}]}{"results":[{"oldID":2,"oldMain":"Banking Files"}]}{"results":[{"oldID":1,"oldMain":"Technologies"}]}

If you inspect the string character by character, you will see that after the closing brace } of the first object, there is no comma and no whitespace before the opening brace [ of the second. To a human eye, this might look like a list of objects printed sequentially. To the JavaScript parser, however, this is syntactically invalid. A JSON array must be enclosed in square brackets [], and a collection of multiple top-level objects requires an array wrapper or explicit separation (like newline-delimited JSON).

The Trap of String Concatenation in PHP

The most common way this happens is in the server-side code generating the response. If your PHP script executes a loop to fetch data and simply echoes each object inside the loop without wrapping them, you end up with exactly this output format:

// ❌ Incorrect PHP logic
foreach ($data as $item) {
    echo json_encode($item); // Outputs: {...}{...}
}

When this string reaches the client and you execute var jsonData = JSON.parse(xhttp.responseText);, the parser reads the first object successfully. It then encounters the { of the second object. Since the current context is not inside an array, it treats this as garbage data appearing after the valid JSON has ended. Hence, the "non-whitespace character" error.

Correcting the Data Structure

To fix this, you must ensure your backend returns a single, valid JSON structure. The standard approach for handling multiple items is to wrap them in an array.

Option 1: Return a Single Array (Recommended)
Modify your PHP script to collect all items into one array before encoding. This allows the frontend to access data via jsonData.results[0], jsonData.results[1], etc., rather than trying to parse a stream of objects.

// Correct PHP logic
$results = [];
foreach ($data as $item) {
    $results[] = $item;
}
header('Content-Type: application/json');
echo json_encode($results); 
// Output: [{"results":[...]}] or just [...] depending on your structure needs

If your PHP data structure is already a list of associative arrays representing the items, you simply need to json_encode that entire array at once. This ensures there are no stray braces floating around the string.

Option 2: Newline-Delimited JSON (NDJSON)
If you strictly need to send multiple independent JSON objects on one line or stream them, you must separate them with newlines (\n) rather than just placing them adjacent. However, note that standard JSON.parse does not support NDJSON natively without splitting the string first. If your data is meant to be a list, wrap it in an array.

Handling the Frontend Error

While fixing the backend is the permanent solution, understanding how to handle this on the frontend prevents silent failures. Always check the Content-Type header and validate the response before parsing.

const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data');
xhr.onload = function() {
    if (xhr.status === 200) {
        // It is often safer to parse only when strictly needed or after validation
        const text = xhr.responseText;
        
        // If the response is truly a single object, this works.
        // If it contains multiple objects without an array wrapper, this throws.
        try {
            var jsonData = JSON.parse(text); 
            console.log(jsonData);
        } catch (e) {
            console.error("Invalid JSON format received:", e.message);
            // Handle the error gracefully here
        }
    }
};
xhr.send();

Why This Happens in Production

Developers often assume that echo json_encode(...) inside a loop creates valid JSON because it prints pretty-looking structures. They forget that json_encode does not automatically add separators between multiple calls, nor does it know the context requires an array wrapper. The error message is technically precise: once the parser hits the first }, it expects either EOF (end of file) or whitespace if that was the end of the document. Finding a { immediately violates that rule.

Fixing this usually involves a simple change in server-side logic to aggregate data into an array structure before serialization, ensuring the payload conforms to the strict RFC 8259 specification expected by the JSON.parse method.

Our network