This would be inefficient. To know if a string is valid JSON it needs to be fully parsed. If it is valid then it is going to do most of that same work again in JSON.parse
.
GitHub - Jack-Works/proposal-json-tryParse: JSON.canParse has been presented in plenary but did not move forward at the time.
There is also
I think it could be useful if we could try an expression, and if it throws return undefined.
Example:
let x = (try JSON.parse(y)) ?? {};
equivalent to:
let x;
try{ x = JSON.parse(y) } catch { x = {}};
There is a lot libraries in npm doing similar stuff, if you search try await you will see a lot libraries which do mostly the same:
const [error, result] = tryCatch(JSON.parse, 'hello');
What all this people want is to use more clean syntax for error handling, similar to something Go already has .
So instead of using such a big construction:
let error, data;
try {
data = JSON.parse('hello');
} catch (e) {
error = e;
}
where you need to use let, 2 code blocks and 3 variables.
What I wan…
It it a very common practice to put JSON.parse() in try/cath to prevent throwing exceptions:
function safeParse(str) {
let parsed;
try {
parsed = JSON.parse(str);
} catch (error) {
console.error(error);
}
return parsed;
}
A lot of community solutions solved this problem in similar way. The weekly download of safe-json-parse is above 600, 000, which is quite impressive. It also shows the importance of this problem.
It is said that try/catch may affect the perfomance, but v4…
1 Like