HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JSON.parse()

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.


String to Object Laboratory

Try parsing the JSON text below. Notice how the status changes from "String" to "JavaScript Object Property":

Input: JSON String
Output: JS Object Access
Type some valid JSON...

Basic Example

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

Parsing Dates

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
Safety Note: Never use eval() to parse JSON data. It is insecure and allows for malicious script execution. Always use JSON.parse().

Browser Support

The JSON.parse() method is part of all modern browsers and the ECMAScript 5 (ES5) standard.


Key Points to Remember

  • JSON.parse() converts a string into a JS object.
  • The input string must be **valid JSON**.
  • It is used to handle data fetched from APIs/Servers.
  • Use the **reviver** function to transform values (like dates) during parsing.
  • It is the secure way to convert text to objects.