Skip to content

Instantly share code, notes, and snippets.

@malipetek
Last active March 11, 2022 03:40
Show Gist options
  • Save malipetek/2bac5ffd53317ff7e498f01a4160c6e1 to your computer and use it in GitHub Desktop.
Save malipetek/2bac5ffd53317ff7e498f01a4160c6e1 to your computer and use it in GitHub Desktop.
JSON parse with error visualization
function JSONparse (content) {
try{
return JSON.parse(content);
} catch (err) {
try {
const offset = parseInt(err.message.match(/position\s+(\d+)/)[1], 10);
const linesUntilError = content.slice(0, offset + 1).split('\n');
const errorLine = linesUntilError.length;
const contentLines = content.split('\n');
const lineOffset = linesUntilError[linesUntilError.length - 1].length - 1;
const message = contentLines.slice(0, errorLine).join('\n') +
'\n' + new Array(lineOffset).fill(' ').join('') +
'👆\n' + contentLines.slice(errorLine).join('\n');
console.log(message);
return {};
} catch (_err) {
// could not show error just throw original one then
throw err;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment