Do you really think JSON.parse and JSON.stringify are that simple?

Pramjeet Ahlawat
Engineering@Wizikey
2 min readJun 11, 2022
JSON.parse error

JSON.parse and JSON.stringify, the functions seem quite simple, they convert a javascript object into a string and vice-versa, but what about when the data is not that ‘simple’. What happens when we pass different data types to the JSON functions? Let’s see:

JSON.parse:

It may seem a little random, but it is actually behaving properly. It doesn’t give you an error if the output is an object or one of the 4 primitive data types – string, number, boolean, and null. So, if you are not absolutely sure of the data source, it is a good practice to always put JSON.parse in try-catch and then validate the data returned.

JSON.strngify:

JSON.strngify is defined way better in the docs like here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify. You may find some behaviors a little odd, but they are properly mentioned in the doc above.

Here is a gist from the above doc:

You should definitely read this on MDN to understand more, it has explained JSON.strngify in very good detail.

As we can see from the examples above, JSON.stringify looks more complex than JSON.parse. It is because the Javascript data can be much more complex than JSON. In some cases, JSON.stringify will throw an error, but in others, it just converts the data into a much simpler format and then JSON.parse just converts it into simpler data than it originally was.

You should keep in mind how your data will change once you convert it using JSON.strngify. It is possible that when you use JSON.stringify on some data and then JSON.parse on the converted data, you may get slightly different results. It is simply because there are some types supported by Javascript but not JSON. So, just be careful about that.

Your original data may have things like undefined, NaN, or may a function, and when you will try to convert it to string and then again to Javascript object, these values will not be there.

Here at Wizikey, we use these functions to stringify data before storing it in cache and then parse it when we read it again. And knowing these details has been useful in preventing some runtime bugs and helps to debug them if some slip in.

So, to answer the question – Do you really think JSON.parse and JSON.stringify are that simple?, for JSON-supported primitive data types and simple Javascript objects, the answer is ‘yes’, but for complex data, you should be careful about how the final data can be different from the original one.

--

--