What is JSON.parse()
text(compulsory)- It is a JSON string that is to be converted as an object.
reviver(optional)- It is an optional parameter and is a function. It acts like a filter and is used to check each key before returning the value. If the value satisfies the condition, the set of actions will be performed. It is used to modify the values that are parsed. This will be discussed in-depth in the later section.
The string that is to be converted should be a valid JSON string. If it isn't so, the SyntaxError exception will be thrown.
As we have not provided the closing quote, the syntax error occurs.
Our input string got converted to an object. We can now access the value corresponding to the key using the dot "." operator.
The following program is in continuation with the above program.
Handling JSON.parse() Special Cases with Revivers
We can see that the reviver function performed transformations on the string. We can also see that our resulting object doesn't have the property which returned undefined, which means it got deleted from the resulting object.
JSON does not allow Date objects. If you want to write a date, write it as a string, then convert it later after parsing to a date object by using the Date() constructor.
We get the date along with the time zone.
In the above program, we can see that undefined was replaced by null as it is a valid JSON value.
JSON objects and arrays can be nested, which means a JSON object can contain another JSON object.
The object gets converted to a JSON string.
Using JSON.parse() Safely
It is important that we use the JSON.parse() function along with the try and catch block to parse our data as even a small error can crash our application, so it is always used with the try and catch block for smooth running.
Let us look at an example-
As we can see, a small error crashed our application, and the further part didn't get executed as the code above it caused an error. This can be prevented using the try and catch block as any error gets caught by the catch block and the further code runs if it is error-free.
As we can see, after implementing the try and catch block, the exception gets handled, and the rest of the code runs properly.
- It takes in two parameters- text(compulsory) and reviver(optional).