JSON text can be converted into a JavaScript object using the JSON.parse() method. Once parsed, the data can be accessed using JavaScript property access techniques such as dot notation or bracket notation.
[Approach]: Using the JSON.parse() Method
The JSON.parse() method parses a valid JSON string and converts it into the corresponding JavaScript value, such as an object or array.
- Store the JSON data as a valid JSON string.
- Pass the JSON string to JSON.parse().
- Store the returned value in a variable.
- Access the required properties using dot notation or bracket notation.
Syntax:
JSON.parse(text[, reviver]);- text: The valid JSON string to be parsed.
- reviver: An optional function that can transform values before they are returned.
Example: Converts JSON text into a JavaScript object and accesses its properties.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON to JavaScript Object</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h2 {
color: #333;
}
b {
color: #555;
}
p {
margin: 10px 0;
}
</style>
</head>
<body>
<h2>Converting JSON Text into JavaScript Object</h2>
<b>JSON Object:</b>
<p id="demo"></p>
<b>Use of JavaScript object:</b>
<p id="demo1"></p>
<script>
let jsonobj = '{ "name":"Brendan Eich","designerof":"JavaScript","bornin":"1961" }';
// Here we convert JSON to object
let obj = JSON.parse(jsonobj);
// Display JSON text
document.getElementById("demo").innerHTML = jsonobj;
// Use JavaScript object to display information
document.getElementById("demo1").innerHTML =
obj.name + ", who was born in " +
obj.bornin + ", was the designer of " +
obj.designerof + ".";
</script>
</body>
</html>
Output:

Accessing Object Properties
After parsing the JSON string, the resulting JavaScript object can be accessed using dot notation or bracket notation.
console.log(obj.name); // Brendan Eich
console.log(obj["designerof"]); // JavaScript
Handling Invalid JSON
JSON.parse() throws a SyntaxError when the provided string is not valid JSON.
const jsonText = '{"name": "Alen",}';
try {
const obj = JSON.parse(jsonText);
} catch (error) {
console.log("Invalid JSON");
}
Output
Invalid JSON
Using try...catch allows you to handle parsing errors without stopping the rest of the program.