Skip to content

Instantly share code, notes, and snippets.

@jgornick
Created September 26, 2012 04:47
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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;
}
@evandrix
Copy link

evandrix commented Jan 27, 2018

The code above^^ fails when the escaped { or } is present in a JSON field value.

FTFY: const json_parse_mult=ss=>{ss=ss.split("\n").map(l=>l.trim()).join("");let start=ss.indexOf("{");let open=0;const res=[];for(let i=start;i<ss.length;i++){if((ss[i]==="{")&&(i<2||ss.slice(i-2,i)!=="\\\"")){open++}else if((ss[i]==="}")&&(i<2||ss.slice(i-2,i)!=="\\\"")){open--;if(open===0){res.push(JSON.parse(ss.substring(start,i+1)));start=i+1}}}return res};

@moeiscool
Copy link

HERO

@AdonousTech
Copy link

Nice! Thanks!!

@RichardTMiles
Copy link

RichardTMiles commented Apr 13, 2023

Thanks all, I took evandrix's code and modified it to help parse malformed json with possible invalid chars before or after. I always add a comment before the code I've sourced with the original link. Should anyone make it better, please share and know I'll be back ;)

// @link https://gist.github.com/jgornick/3786127
export function parseMultipleJson(ss) {

    ss = ss.split("\n").map(l => l.trim()).join("");

    let start = ss.indexOf("{");

    let open = 0;

    const res : any[] = [];

    for (let i = start; i < ss.length; i++) {

        if ((ss[i] === "{") && (i < 2 || ss.slice(i - 2, i) !== "\\\"")) {

            open++

            if (open === 1) {

                start = i

            }

        } else if ((ss[i] === "}") && (i < 2 || ss.slice(i - 2, i) !== "\\\"")) {

            open--;

            if (open === 0) {

                res.push(JSON.parse(ss.substring(start, i + 1)));

                start = i + 1

            }

        }

    }

    return res

}

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