JavaScript JSON.parse() Example

The JavaScript JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON.


JSON object provides two methods to convert Javascript object to JSON and vice versa:
  • JSON.parse() - Parses a JSON string and returns a JavaScript object
  • JSON.stringify() - Convert a JavaScript object to a JSON string
In this example, we will demonstrate how to parse a JSON string and returns a JavaScript object using JSON.parse() method.

JavaScript JSON.parse() Example

Here is a simple example using JSON.parse() method, which returns Javascript object:
var text = JSON.parse( '{ "firstName" : "Ramesh", "lastName" : "Fadatare",  "emailId" : "ramesh@gmail.com",  "age" : "29"  }');
console.log(text);
Output:
{firstName: "Ramesh", lastName: "Fadatare", emailId: "ramesh@gmail.com", age: "29"}
Note that above javascript object is printed in the console.
How to use the reviver function:
/*replace the value of "city" to upper case:*/
var text = '{ "name":"John", "age":"39", "city":"New York"}';
var obj = JSON.parse(text, function (key, value) {
  if (key == "city") {
    return value.toUpperCase();
  } else {
    return value;
  }
});
console.log(text);
Output:
{ "name":"John", "age":"39", "city":"New York"}
More examples:
JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null

Reference


Comments