chiborg chiborg - 6 months ago 9
JSON Question

Split string into JSON and non-JSON part

I have a string like this:

var s = '{ "foo": { "bar": { "baz": 5 } } } Some more content';


Is there a reliable way in JavaScript to split the string into the JSON and non-JSON part? The string always begins with valid JSON, but other than that the JSON can contain anything, so tricks like counting braces won't work.

The best option I see at the moment is to use the json-lint module to get the position of the error and split at the error position.

Any other ideas?

Answer

Using the same approach as KevBot but potential elimination a lot of try {} catch(e) {}:

var s = '{ "foo": { "bar": { "baz": 5 } } } Some mo}re }content';
var offset = s.length + 1;
while (offset > 0) {
    offset = s.lastIndexOf('}', offset - 1);
    var maybe_json = s.slice(0, offset + 1);
    try {
        var json = JSON.parse(maybe_json);
    break;
    } catch (e) {}
}
var rest = s.slice(offset + 1);

console.log(json); // { "foo": { "bar": { "baz": 5 } } }
console.log(rest); // " Some mo}re }content"