JSON.safeParse():call JSON.parse() in try/catch?

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) {

  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.5 of V8 has already solved this problem. I will provide more benchmark result about this. And since a lot of people call JSON.parse() in try/catch anyway, performance is not a practical problem.

Why not add JSON.safeParse() to ECMAScript?


1 Like

Well the goal is not to "prevent exceptions", it is to handle errors from invalid input. For which try/catch is the normal and idiomatic solution, and the code in the catch block is application-specific.

No, it shows that safe-json-parse is used as a dependency of two other popular packages (video.js and body). It does not show that people perceive this as a problem or that they prefer this style (actually, any of the three styles offered by that package) over the normal try/catch.

1 Like

I think the safeParse method is nessary, it reminds developer that JSON.parse is not safety, when you use it, you should be careful. by the way, json is the most important data structure in js you know, safeParse will improve the robustness of the program, and less try/catch block.

That sounds like an argument for providing a better name for JSON.parse(), not for changing its behavior. e.g. would you be happy if we provided a JSON.attemptParse() or JSON.dangerouseParse() that functioned exactly the same as JSON.parse(), but its naming reminds you that you should catch and handle any errors (or don't catch them if you're certain an error should not be thrown)?

(edit: Not that I would encorage that we do this kind of renaming - I was just trying to figure out this point of view)

JSON.parse is not unsafe. It can throw exceptions, like any other function that has some requirement on its input. Which in this case, is that the input must be well-formed JSON. I think that's obvious from the name "parse".

Second, I don't see how swallowing exceptions improves the robustness of a program.

If your main concern is that try/catch blocks are too verbose, then adding a single function wrapper doesn't solve anything. You want more concise, generic syntax.


Yes - I would add that its equally likely for someone to forget to handle the error from JSON.parse(), as it is for someone to forget to handle the fact that JSON.safeParse() may return undefined if you received invalid JSON. In the first case, you'll get a nice error explaining exactly what went wrong. In the second case, you'll probably end up with a less useful error like "Cannot read property 'someExpectedJSONProperty' of undefined"