Data received from a web server is always a string. To use this data as a JavaScript object, you must convert it. The JSON.parse() method parses a JSON string and returns a JavaScript object.
Try parsing the JSON text below. Notice how the status changes from "String" to "JavaScript Object Property":
Imagine we receive this text from a web server:
let text = '{"name":"John", "age":30, "city":"New York"}';
Use JSON.parse() to convert it into a JavaScript object:
let obj = JSON.parse(text);
// Now you can access it like an object
console.log(obj.name); // John
JSON does not allow date objects. If you need to include a date, write it as a string. You can convert it back into a date object later using the reviver function (the second parameter of JSON.parse).
let text = '{"name":"John", "birth":"1986-12-14"}';
let obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});
console.log(obj.birth.getFullYear()); // 1986
eval() to parse JSON data. It is insecure and allows for malicious script execution. Always use JSON.parse().
The JSON.parse() method is part of all modern browsers and the ECMAScript 5 (ES5) standard.