Fix unexpected non-whitespace character after JSON

What the 'unexpected non-whitespace character after JSON' error means, how to find the extra content, and which fixes keep your data intact.

This error means a parser read one complete, valid JSON value and then found more content after it. JSON text may contain exactly one top-level value, with only whitespace before or after it. Anything else that follows, such as a second object, a stray brace or an invisible character, triggers the error. The fix depends on what that trailing content is and whether it belongs to your data.

What the error message tells you

In Chromium-based browsers and Node.js, JSON.parse reports the problem as an unexpected non-whitespace character after JSON at a given position. Some versions also add a line and column. Firefox reports similar wording, followed by a line and column of the JSON data. Python's json module raises an 'Extra data' error for the same condition. The position is the useful part. It points to the first character after the end of the first complete value, which is where the unexpected content begins.

JSON.parse('{"a":1}{"b":2}');
// SyntaxError: Unexpected non-whitespace character after JSON at position 7

# Python
json.loads('{"a":1}{"b":2}')
# json.decoder.JSONDecodeError: Extra data: line 1 column 8 (char 7)

The JavaScript position is counted from zero, so position 7 is the eighth character. In this example it is the opening brace of the second object. The first object, {"a":1}, is exactly seven characters long. Exact message wording varies between engine versions, so rely on the reported position rather than matching the text of the message.

Under the JSON standard, only four characters count as whitespace: space, horizontal tab, line feed and carriage return. Trailing spaces and newlines are therefore harmless. A trailing non-breaking space, zero-width space or null byte is not whitespace in this sense, and it produces this error even though you cannot see it.

Common causes and how to tell them apart

Each of the following can produce the same message. None should be treated as the confirmed cause until you have looked at the actual characters at the reported position.

Likely cause | What you see at the reported position | Typical source
Several JSON values joined together | Another { or [ often directly after } or ], or on the next line | Log files, NDJSON or JSON Lines exports, streamed responses, appending to a file
Extra closing bracket or brace | A lone } or ] | Hand edits, merge conflicts, string-built JSON
A bracket closed too early | A comma or key that should still be inside the object | Mismatched nesting in hand-written or templated JSON
Server output after the JSON body | HTML, a warning message or debug text | Backend code that prints something after sending the JSON
Invisible trailing characters | Nothing visible; the code point reveals it | Copying from documents, chat apps or web pages; fixed-size buffers padded with null bytes
Data accumulated twice | A repeat of the start of the payload | Stream handlers that append the same chunk more than once

To tell these apart, print a slice of the raw text around the reported position and the code point of the character there. JSON.stringify makes control characters such as null bytes visible as escapes. It does not escape characters such as the zero-width space, so the code point check is what exposes those.

const pos = 7; // position from the error message
console.log(JSON.stringify(text.slice(Math.max(0, pos - 20), pos + 20)));
console.log(text.codePointAt(pos).toString(16));

Inspect the text exactly as the parser received it. With fetch, read response.text() rather than calling response.json(), and log the result. The browser's network panel also shows the raw response body. A formatted preview in an editor or viewer may already have cleaned up or hidden the problem.

Targeted fixes

The fix should match the cause you have confirmed. Deleting whatever follows the first value makes the error go away, but it may also discard real data.

  • Multiple records, one per line: parse each line separately instead of the whole text at once.
  • Multiple values meant as one document: change the producer so it writes a single JSON array, or wrap the values in brackets and separate them with commas.
  • Extra or misplaced brackets: correct the nesting at the source, and use a validator to confirm the structure afterwards.
  • Server output after the body: find and remove whatever writes output after the JSON response, such as stray echo or print statements or error messages rendered into the body.
  • Invisible trailing characters: remove only the specific code points you identified, and fix the copy or buffer step that introduced them.
  • Duplicated chunks: review the stream or response handling so each chunk is appended exactly once.
// One JSON value per line (NDJSON / JSON Lines)
const records = text
  .split(/\r?\n/)
  .filter(line => line.trim() !== '')
  .map(line => JSON.parse(line));

Sometimes you cannot change the source and you knowingly want only the first value. In that case, parse that value explicitly and keep the remainder so you can check what you are dropping. In Python, raw_decode returns the parsed value together with the index where it ended.

import json

value, end = json.JSONDecoder().raw_decode(text)
rest = text[end:]
if rest.strip():
    print('Ignored trailing content:', repr(rest[:80]))

What a formatter or validator actually changes

In this context, "formatting" means arranging characters with indentation and line breaks. It has nothing to do with fonts or styled Unicode letters. Pretty-printing and minifying change only the whitespace between tokens, so the data itself stays the same. A validator changes nothing; it only reports whether the text parses and where it fails. Neither one will fix this error, because the problem lies in the content and not in its layout.

Tools described as "repairing" JSON are different. They change the stored characters. When such a tool resolves this error by dropping trailing content, or by guessing where brackets belong, the output may parse cleanly but contain different data from what you intended. Compare the repaired output with the original before you rely on it.

Re-serializing JSON through a JavaScript parse-and-stringify cycle can also change it in quieter ways. Integers beyond the safe integer range can lose precision. When a key appears twice, only the last value survives. Object keys that look like integers are moved ahead of other keys and sorted numerically. If exact numbers or key order matter, check that the tool you use preserves them.

Keeping JSON usable after copying or sharing

Copying JSON through word processors, chat apps, PDFs or rich-text editors can add characters that are not JSON whitespace. Non-breaking spaces and zero-width characters at the end of a snippet are a common source of this error. Curly quotes cause a different error, near the start of the text. Sharing JSON as a file, or inside a plain-text code block, lowers the risk. Other people can then paste it without picking up formatting artifacts.

Indented JSON is easier for people to scan and to compare in diffs. Minified JSON is more compact for transfer. Both parse to the same data. No tested evidence was available here on how particular screen readers or specific destinations handle pasted JSON. Check your own target environment rather than assuming one successful paste will work everywhere.

Is reformatting or repair the right step for you?

Use a validator first. It locates the problem without altering anything, which makes it the safest starting point for this error. Pretty-printing is suitable when you need readable output for review, because it preserves the data. Automatic repair suits only throwaway or exploratory work, since the convenience comes at the cost of possibly losing or changing data without notice. When the JSON will feed a production system, a database or an audit trail, keep the original raw text unchanged and fix the producer instead of the output. The plain, unmodified text is the reliable reference for debugging and for showing what was actually received.