1. javascript
  2. /references
  3. /json-parse

JSON.parse()

The JSON.parse() function is a built-in JavaScript method that allows you to parse a JSON string and convert it into a JavaScript object. This can be useful when receiving data from a web server, as the data is often sent as a JSON string that you can then convert into a JavaScript object to be used in your code.

To use the JSON.parse() function, you pass it a string containing a JSON document, and it returns a JavaScript object that represents the data in the string. For example, consider the following JSON string:

var jsonString = '{"name": "John Doe", "age": 35, "employed": true}';

To convert this string into a JavaScript object, you can use the JSON.parse() function like this:

var data = JSON.parse(jsonString);

This code will create a new JavaScript object named data that contains the data from the JSON string. You can then access the individual properties of the object using dot notation or bracket notation:

console.log(data.name); // Outputs "John Doe"
console.log(data["age"]); // Outputs 35

In addition to parsing simple objects, the JSON.parse() function can also parse arrays and nested data structures. For example, consider the following JSON string:

var jsonString = '{"name": "John Doe", "skills": ["JavaScript", "HTML", "CSS"]}';

To convert this string into a JavaScript object, you can use the JSON.parse() function in the same way:

var data = JSON.parse(jsonString);

This time, the data object will contain two properties: "name" and "skills". The "skills" property will be an array containing three strings. You can access the elements of the array using bracket notation:

console.log(data.skills[0]); // Outputs "JavaScript"