JSON.parse()
The JSON.parse()
static method in JavaScript is used to parse a JSON string and convert it into a corresponding JavaScript object or value. It optionally allows for a reviver
function to perform transformations on the resulting object before it is returned.
Syntax
JSON.parse(text)
JSON.parse(text, reviver)
Parameters
Parameter | Description |
---|---|
text | A valid JSON string to be parsed. It must conform to the JSON standard. |
reviver | Optional. A function that transforms the results. This function is called for each key-value pair in the parsed object. |
Return Value
The JSON.parse()
method returns the JavaScript object or value resulting from parsing the given JSON string.
If the text
is not a valid JSON string, the method throws a SyntaxError
.
Examples
1. Parsing a JSON String
This example demonstrates how to parse a JSON string into a JavaScript object.
const jsonString = '{"name": "Arjun", "age": 30, "city": "New York"}';
const parsedObject = JSON.parse(jsonString);
console.log(parsedObject);
Output
{ name: 'Arjun', age: 30, city: 'New York' }
- The
JSON.parse()
method converts the JSON string into a JavaScript object.
2. Parsing with a Reviver Function
The reviver
function allows custom transformation of the parsed object. This example converts the values to uppercase for specific keys.
const jsonString = '{"name": "Arjun", "age": 30, "city": "New York"}';
const parsedObject = JSON.parse(jsonString, (key, value) => {
if (key === "name" || key === "city") {
return value.toUpperCase();
}
return value;
});
console.log(parsedObject);
Output
{ name: 'ARJUN', age: 30, city: 'NEW YORK' }
- The
reviver
function is called for each key-value pair, allowing custom transformations. - In this case, the
name
andcity
values are converted to uppercase.
3. Parsing an Invalid JSON String
If the JSON string is invalid, a SyntaxError
is thrown.
try {
const invalidJson = '{"name": "Arjun", "age": 30, city: "New York"}'; // Missing quotes around "city"
JSON.parse(invalidJson);
} catch (error) {
console.error("Parsing error:", error.message);
}
Output
Parsing error: Expected double-quoted property name in JSON at position 29
- An error occurs because the JSON string is invalid.
- Use
try...catch
to handle parsing errors gracefully.
4. Parsing Nested JSON
The JSON.parse()
method can handle nested JSON structures.
const nestedJson = '{"person": {"name": "Arjun", "age": 30}, "city": "New York"}';
const parsedObject = JSON.parse(nestedJson);
console.log(parsedObject.person.name); // Access nested data
Output
Arjun
- The
JSON.parse()
method converts the nested JSON string into a JavaScript object. - Access nested data using dot notation.