Skip to content

Instantly share code, notes, and snippets.

@adambom
Last active March 5, 2022 17:30
Show Gist options
  • Save adambom/5347590 to your computer and use it in GitHub Desktop.
Save adambom/5347590 to your computer and use it in GitHub Desktop.
parsing incomplete json
function parseIncompleteJSON(jsonString, stopIndex) {
try {
return {
json: JSON.parse(jsonString),
stoppedAt: stopIndex
};
} catch (e) {
return parseIncompleteJSON(jsonString.substring(0, jsonString.length - 1), jsonString.length - 1);
}
}
@dionyziz
Copy link

For what it's worth, this may cause a stack overflow for large JSON files.

@franciskim
Copy link

Clever, but: Uncaught RangeError: Maximum call stack size exceeded

@shayan6
Copy link

shayan6 commented Mar 5, 2022

hi @dionyziz , @franciskim
try this one:

let str = [{ "json": "incomplete"}, {"json": "partially complete"};

if (str.indexOf('[') === 0 || str.indexOf('{') === 0) {
str = parseIncompleteJSON(str.slice(0, str.lastIndexOf('}') + 1));
}

function parseIncompleteJSON (jsonString, i = 0) {

if (jsonString[0] == '[' && i == 0) { // agar json array of string hai to first time srf ']' lagay ga
  jsonString += ']'; 
} else if (jsonString[0] == '[') {
  jsonString = jsonString.slice(0, jsonString.length - 1).concat('}', ']');
} else {
  jsonString += '}';
}

if (i == 10) { 
  return jsonString;
}

try {
  return JSON.parse(jsonString);
} catch (e) {
  return parseIncompleteJSON(jsonString, ++i);
}

}

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