Skip to content

Instantly share code, notes, and snippets.

@jgornick
Created September 26, 2012 04:47
Show Gist options
  • Save jgornick/3786127 to your computer and use it in GitHub Desktop.
Save jgornick/3786127 to your computer and use it in GitHub Desktop.
JavaScript: Parse multiple JSON documents from string
/**
* Parses a string containing one or multiple JSON encoded objects in the string.
* The result is always an array of objects.
*
* @param {String} data
* @return {Array}
*/
function parseJson(data) {
data = data.replace('\n', '', 'g');
var
start = data.indexOf('{'),
open = 0,
i = start,
len = data.length,
result = [];
for (; i < len; i++) {
if (data[i] == '{') {
open++;
} else if (data[i] == '}') {
open--;
if (open === 0) {
result.push(JSON.parse(data.substring(start, i + 1)));
start = i + 1;
}
}
}
return result;
}
@andersnm
Copy link

andersnm commented Mar 5, 2025

@RichardTMiles FYI these work with JSON.parse but crashes parseMultipleJson "Unexpected end of JSON input"

parseMultipleJson("{\"hallo}\": 1}");
parseMultipleJson("{\"hallo\}\": 1}");
parseMultipleJson("{\"hallo\": \"world}\"}");
parseMultipleJson("{\"hallo\": \"world\}\"}");

Don't have a fix yet, investigating options currently. Gonna need something like this within the next 3-4 weeks, so I'll share a fix then if we need it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment