-
-
Save AdonousTech/31a2c38c89f7c9fcaefe230d9d37cb7b to your computer and use it in GitHub Desktop.
JavaScript: Parse multiple JSON documents from string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment