Skip to content

Instantly share code, notes, and snippets.

@loverde
Forked from kekscom/FixJson.js
Created January 4, 2019 19:46
Show Gist options
  • Save loverde/062f732dba8d29165db667348fb76601 to your computer and use it in GitHub Desktop.
Save loverde/062f732dba8d29165db667348fb76601 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment