Last active
January 4, 2019 19:46
-
-
Save kekscom/10925007 to your computer and use it in GitHub Desktop.
Fix truncated JSON data.
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
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
Does only work for cuts on end, not for booleans, not for escaped special chars - yet.