Last active
July 6, 2021 18:10
-
-
Save ziomarco/7912b0ebc2fdf55e2849fa2e3142d76e to your computer and use it in GitHub Desktop.
fast_broken_json_parser
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
export class BrokenJSONParser { | |
static forceParseNested(input: string) { | |
if (!input) return null; | |
let stringToParse = input; | |
try { | |
const parsed = JSON.parse(stringToParse); | |
return parsed; | |
} catch (e) { | |
const errorSearchString = 'at position '; | |
const startIndex = e.message.indexOf(errorSearchString); | |
if (!startIndex || startIndex === -1) { | |
return null; | |
} | |
let errorPosition = e.message.slice(startIndex + errorSearchString.length, e.message.length); | |
errorPosition = !isNaN(+errorPosition) ? +errorPosition : null; | |
if (!errorPosition) { return null; } | |
if (stringToParse[errorPosition] === '"') { | |
stringToParse = this.setCharAt(stringToParse, (errorPosition), ''); | |
return this.forceParseNested(stringToParse); | |
} | |
if (stringToParse[errorPosition - 1] === '"' && stringToParse[errorPosition - 2] === "{") { | |
stringToParse = this.setCharAt(stringToParse, (errorPosition - 3), ''); | |
return this.forceParseNested(stringToParse); | |
} | |
return null; | |
} | |
} | |
private static setCharAt(str, index, chr) { | |
if (index > str.length - 1) return str; | |
return str.substring(0, index) + chr + str.substring(index + 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment