Introduction:
Welcome to our comprehensive guide on mastering JSON parsing in JavaScript. In this lesson, we’ll delve into the intricacies of using the JSON.parse() method, exploring real-world examples to solidify your understanding. From handling invalid JSON to working with reviver functions, we’ve got you covered. Let’s dive into the world of JSON parsing excellence!
Here’s a brief explanation of JSON.parse() along with some examples:
JSON.parse(text[, reviver])
text:
The JSON string to be parsed.
Examples:
Basic Usage:
const jsonString = '{"name": "Omar", "age": 20, "city": "Cairo"}';
const parsedObject = JSON.parse(jsonString);
console.log(parsedObject);
// Output: { name: 'John', age: 30, city: 'New York' }
const jsonArrayString = '[1, 2, 3, 4, 5]'; const parsedArray = JSON.parse(jsonArrayString); console.log(parsedArray); // Output: [1, 2, 3, 4, 5]
const jsonStringWithDate = '{"name": "Alice", "dob": "1990-01-15T00:00:00.000Z"}';
const reviverFunction = (key, value) => {
if (key === 'dob') {
return new Date(value);
}
return value;
};
const parsedObjectWithDate = JSON.parse(jsonStringWithDate, reviverFunction);
console.log(parsedObjectWithDate);
// Output: { name: 'Alice', dob: 1990-01-15T00:00:00.000Z }
In this example, a reviver function is used to convert the “dob” property value into a JavaScript Date object.
const invalidJsonString = '{"name": "Mike", "age": 25, "city": "Chicago",}';
try {
const parsedObject = JSON.parse(invalidJsonString);
console.log(parsedObject);
} catch (error) {
console.error('Invalid JSON:', error.message);
// Output: Invalid JSON: Unexpected token '}' in JSON at position 44
}
Basic Usage:complete code with Explanation
Here’s a simple HTML example demonstrating the basic usage of JSON.parse():
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON.parse() Example</title>
</head>
<body>
<script>
// JSON string
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
// Parsing JSON string
const parsedObject = JSON.parse(jsonString);
// Displaying the parsed object in the console
console.log(parsedObject);
// Accessing properties of the parsed object
const name = parsedObject.name;
const age = parsedObject.age;
const city = parsedObject.city;
// Displaying properties in the HTML body
document.body.innerHTML = `
<h1>JSON.parse() Example</h1>
<p>Name: ${name}</p>
<p>Age: ${age}</p>
<p>City: ${city}</p>
`;
</script>
</body>
</html>
Explanation:

Handling Arrays:complete code in html with explanation
Here’s an HTML example demonstrating the basic usage of JSON.parse() with an array:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON.parse() Array Example</title>
</head>
<body>
<script>
// JSON array string
const jsonArrayString = '[1, 2, 3, 4, 5]';
// Parsing JSON array string
const parsedArray = JSON.parse(jsonArrayString);
// Displaying the parsed array in the console
console.log(parsedArray);
// Accessing elements of the parsed array
const firstElement = parsedArray[0];
const lastElement = parsedArray[parsedArray.length - 1];
// Displaying array elements in the HTML body
document.body.innerHTML = `
<h1>JSON.parse() Array Example</h1>
<p>Parsed Array: ${parsedArray}</p>
<p>First Element: ${firstElement}</p>
<p>Last Element: ${lastElement}</p>
`;
</script>
</body>
</html>
Explanation:

Here’s an HTML example demonstrating the usage of JSON.parse() with a reviver function:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON.parse() with Reviver Function Example</title>
</head>
<body>
<script>
// JSON string with a date
const jsonStringWithDate = '{"name": "Alice", "dob": "1990-01-15T00:00:00.000Z"}';
// Reviver function to convert date strings to Date objects
const reviverFunction = (key, value) => {
if (key === 'dob') {
return new Date(value);
}
return value;
};
// Parsing JSON string with reviver function
const parsedObjectWithDate = JSON.parse(jsonStringWithDate, reviverFunction);
// Displaying the parsed object in the console
console.log(parsedObjectWithDate);
// Accessing properties of the parsed object
const name = parsedObjectWithDate.name;
const dob = parsedObjectWithDate.dob;
// Displaying properties in the HTML body
document.body.innerHTML = `
<h1>JSON.parse() with Reviver Function Example</h1>
<p>Name: ${name}</p>
<p>Date of Birth: ${dob}</p>
`;
</script>
</body>
</html>
Explanation:

Handling Invalid JSON:complete code with explanation
Here’s an HTML example demonstrating the handling of invalid JSON using a try-catch block:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Handling Invalid JSON Example</title>
</head>
<body>
<script>
// Invalid JSON string with a syntax error (extra comma)
const invalidJsonString = '{"name": "Mike", "age": 25, "city": "Chicago",}';
try {
// Attempt to parse the invalid JSON string
const parsedObject = JSON.parse(invalidJsonString);
// Displaying the parsed object in the console
console.log(parsedObject);
// Accessing properties of the parsed object
const name = parsedObject.name;
const age = parsedObject.age;
const city = parsedObject.city;
// Displaying properties in the HTML body
document.body.innerHTML = `
<h1>Handling Invalid JSON Example</h1>
<p>Name: ${name}</p>
<p>Age: ${age}</p>
<p>City: ${city}</p>
`;
} catch (error) {
// Catching and handling the error if JSON parsing fails
console.error('Invalid JSON:', error.message);
// Displaying an error message in the HTML body
document.body.innerHTML = `
<h1>Handling Invalid JSON Example</h1>
<p>Error: ${error.message}</p>
`;
}
</script>
</body>
</html>
Explanation:
Here are some common parsing exceptions:
SyntaxError: Occurs when the JSON string has a syntax error.
try {
const invalidJsonString = '{"name": "Mike", "age": 25, "city": "Chicago",}';
const parsedObject = JSON.parse(invalidJsonString);
console.log(parsedObject);
} catch (error) {
console.error('SyntaxError:', error.message);
}
Output:
SyntaxError: Unexpected token ‘}’ in JSON at position 44
TypeError: Can occur if the provided JSON is not a string.
try {
const notAString = { name: 'Alice', age: 30, city: 'London' };
const parsedObject = JSON.parse(notAString);
console.log(parsedObject);
} catch (error) {
console.error('TypeError:', error.message);
}
Output:
TypeError: First argument must be a string, ArrayBuffer, or an array or array-like object.
Other Errors: Other types of errors may occur depending on the content and structure of the JSON string.
try {
const invalidJsonString = '{"name": "Bob", "age": "thirty"}';
const parsedObject = JSON.parse(invalidJsonString);
console.log(parsedObject);
} catch (error) {
console.error('Error:', error.message);
}
Output:
Error: JSON.parse: end of data after property value in JSON at line 1 column 29 of the JSON data
Here’s an HTML example demonstrating the parsing of dates using JSON.parse() and handling potential exceptions:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Parsing Dates with JSON.parse() Example</title>
</head>
<body>
<script>
// JSON string with a date
const jsonStringWithDate = '{"name": "Alice", "dob": "1990-01-15T00:00:00.000Z"}';
try {
// Parsing JSON string with reviver function to convert date strings to Date objects
const parsedObjectWithDate = JSON.parse(jsonStringWithDate, (key, value) => {
if (key === 'dob') {
return new Date(value);
}
return value;
});
// Displaying the parsed object in the console
console.log(parsedObjectWithDate);
// Accessing properties of the parsed object
const name = parsedObjectWithDate.name;
const dob = parsedObjectWithDate.dob;
// Displaying properties in the HTML body
document.body.innerHTML = `
<h1>Parsing Dates with JSON.parse() Example</h1>
<p>Name: ${name}</p>
<p>Date of Birth: ${dob.toISOString()}</p>
`;
} catch (error) {
// Catching and handling the error if JSON parsing fails
console.error('Error:', error.message);
// Displaying an error message in the HTML body
document.body.innerHTML = `
<h1>Parsing Dates with JSON.parse() Example</h1>
<p>Error: ${error.message}</p>
`;
}
</script>
</body>
</html>
Explanation:
Here’s an example to illustrate the potential dangers of parsing functions from JSON.
This example is for educational purposes only, and it’s crucial to understand the risks involved:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Parsing Functions with JSON.parse() Example</title>
</head>
<body>
<script>
// JSON string with a function (for educational purposes only)
const jsonStringWithFunction = '{"name": "Alice", "age": 30, "func": "function(){ alert(\'Danger!\'); }"}';
try {
// Parsing JSON string with potential function
const parsedObjectWithFunction = JSON.parse(jsonStringWithFunction);
// Accessing properties of the parsed object
const name = parsedObjectWithFunction.name;
const age = parsedObjectWithFunction.age;
// Attempting to execute the parsed function (for educational purposes only)
if (parsedObjectWithFunction.func && typeof parsedObjectWithFunction.func === 'function') {
parsedObjectWithFunction.func();
}
// Displaying properties in the HTML body
document.body.innerHTML = `
<h1>Parsing Functions with JSON.parse() Example</h1>
<p>Name: ${name}</p>
<p>Age: ${age}</p>
`;
} catch (error) {
// Catching and handling the error if JSON parsing fails
console.error('Error:', error.message);
// Displaying an error message in the HTML body
document.body.innerHTML = `
<h1>Parsing Functions with JSON.parse() Example</h1>
<p>Error: ${error.message}</p>
`;
}
</script>
</body>
</html>
Explanation:
Again, parsing functions from JSON is not recommended in practice due to security risks. It’s important to sanitize and validate JSON data, ensuring that it does not contain executable code.
A quiz questions related to the JSON parsing examples provided in this conversation. The questions cover various aspects of using JSON.parse() in JavaScript. Please note that the questions assume a basic understanding of the concepts presented in the examples.
A) To stringify JSON data
B) To parse JSON data into a JavaScript object
C) To validate JSON syntax
A) JSON.stringify()
B) JSON.parse()
C) JSON.revive()
A) TypeError
B) SyntaxError
C) RangeError
A) To improve performance
B) To avoid security vulnerabilities
C) To enhance readability
A) To log errors during parsing
B) To convert date strings to Date objects
C) To stringify JSON data
A) Arrays
B) Dates
C) Booleans
A) It slows down the parsing process
B) It can lead to security vulnerabilities
C) It improves code readability
A) String
B) Function
C) Number
A) Using date.toISOString()
B) Using date.toString()
C) Using date.toUTCString()
A) Converts date strings to Date objects
B) Converts Date objects to date strings
C) Logs errors during parsing
A) code
B) description
C) message
A) Missing colon
B) Extra comma
C) Missing quotation marks
A) To improve code performance
B) To gracefully handle and recover from errors
C) To skip code execution
A) The catch block would be executed
B) The try block would be skipped
C) The parsed object would be logged to the console
A) It is a recommended practice for enhancing code flexibility.
B) It is a common way to improve code readability.
C) It is not recommended due to security risks.
1-B
2-B
3-B
4-B
5-B
6-B
7-B
8-B
9-A
10-A
11-C
12-B
13-B
14-C
15-C