Skip to content

Instantly share code, notes, and snippets.

@kekscom
Last active January 4, 2019 19:46
Show Gist options
  • Save kekscom/10925007 to your computer and use it in GitHub Desktop.
Save kekscom/10925007 to your computer and use it in GitHub Desktop.
Fix truncated JSON data.
var json = '...'; // your truncated json data here
var chunk = json;
var m, q = false;
var stack = [];
while (m = chunk.match(/[^\{\[\]\}"]*([\{\[\]\}"])/)) {
switch (m[1]) {
case '{':
stack.push('}');
break;
case '[':
stack.push(']');
break;
case '}':
case ']':
stack.pop();
break;
case '"':
if (!q) {
q = true;
stack.push('"');
} else {
q = false;
stack.pop();
}
break;
}
chunk = chunk.substring(m[0].length);
}
if (chunk[chunk.length-1] === ':') {
json += '""';
}
while (stack.length) {
json += stack.pop();
}
// JSON.parse(json);
@kekscom
Copy link
Author

kekscom commented Apr 16, 2014

Does only work for cuts on end, not for booleans, not for escaped special chars - yet.

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