DEV Community

Mohammed Awny
Mohammed Awny

Posted on Fully Autonomous

Why {"id":1}{"id":2} fails JSON.parse() — and when to wrap it in an array

If you copy two JSON objects from a log, an AI response, or two API outputs, you may end up with this:

{"id":1}{"id":2}
Enter fullscreen mode Exit fullscreen mode

Each object is valid on its own. Together they are not one JSON document. JSON.parse() reads the first object, then encounters more content where it expects the input to end. In recent V8 versions you may see “Unexpected non-whitespace character after JSON.” In Python, json.loads() often reports “Extra data.”

The right fix depends on what the two objects represent.

One collection? Make an array

If these are two entries in a single document, wrap them in brackets and separate them with a comma:

[
  {"id":1},
  {"id":2}
]
Enter fullscreen mode Exit fullscreen mode

Now JSON.parse() returns an array of two entries. This is what you want for a JSON file or a single API response containing a list. Do not blindly insert a comma between objects without the array: {"id":1},{"id":2} is still not a valid single JSON document.

Separate events? Keep one record per line

Some logs use NDJSON (newline-delimited JSON): each line is an independent JSON value. That format is useful for event streams, but the whole file is not a single JSON document:

{"id":1}
{"id":2}
Enter fullscreen mode Exit fullscreen mode

Parse lines separately when your producer really guarantees one complete JSON value per line:

const records = raw
  .split(/\r?\n/)
  .filter(line => line.trim())
  .map(line => JSON.parse(line));
Enter fullscreen mode Exit fullscreen mode

That snippet is not suitable for pretty-printed, multiline objects or incomplete stream chunks. Use a proper streaming parser for those. Converting an event stream into one array also changes its meaning and forces you to hold the collection in memory.

Before applying an automatic repair

Check that both objects are complete and that you intend a collection. If the second object ends halfway through a string, the missing data cannot be inferred. And if the response starts with <html>, you likely fetched an error page rather than JSON; inspect the HTTP response instead of changing its syntax.

I maintain QuickTiny. Its free JSON formatter and validator detected the exact {"id":1}{"id":2} example above and offered to wrap the two complete objects in an array. I checked the result in the browser: [{"id":1},{"id":2}] is valid. Use it only when an array matches your data model; it does not repair truncated data.

Have you seen concatenated objects in an API response, an event log, or an AI output? The origin usually tells you which representation is correct.

Top comments (0)