JavaScript JSON.parse(text, reviver
The JSON.parse(text, reviver)
method in JavaScript is used to parse a JSON string and convert it into a JavaScript value or object. This method is part of the JSON
object, which provides utilities for working with JSON data.
Syntax:
Parameters:
text
: A valid JSON string that you want to parse into a JavaScript value. If the string is not valid JSON, aSyntaxError
will be thrown.reviver
(optional): A function that can be used to transform the parsed values. It receives two arguments: the key and the value of each property in the parsed object. You can return a modified value orundefined
to omit the property from the resulting object.
Return Value:
- Returns the JavaScript value or object that the JSON string represents.
Example 1: Basic Usage
In this example, a JSON string is parsed into a JavaScript object.
Example 2: Using a Reviver Function
The reviver function allows you to transform the values during the parsing process.
In this example, the reviver function converts the age
property from a string to a number.
Example 3: Omitting Properties with Reviver
You can also use the reviver function to omit properties from the resulting object.
In this case, the reviver function removes the password
property from the resulting object.
Example 4: Handling Nested Objects
The reviver function can be useful for transforming nested objects as well.
Here, the reviver function converts the zip
code in a nested object to a number.
Summary:
JSON.parse(text, reviver)
is used to convert a JSON string into a JavaScript value or object.- The
text
parameter must be a valid JSON string; otherwise, it throws aSyntaxError
. - The optional
reviver
function allows for transformation of the parsed values, including modifying or omitting properties. - This method is essential for deserializing JSON data received from APIs or other sources into usable JavaScript objects.