JavaScript JSON parse() Method

JSON.parse() method is used to parse a JSON string and returns a JavaScript object

Syntax

JSON.parse(text, reviver)

Parameters

  1. text(required): This is the string to be parsed as JSON.
  2. reviver(optional): A function that can transform the object values before they are returned. The reviver function is called for each member of the object. If a member contains nested objects, the nested objects are transformed before the parent object.

Return value

Returns Object, Array, Bool or null value corresponding to the given JSON text

Visual Representation

Visual Representation of JavaScript JSON parse() Method

Example 1: How to Use JSON parse() method

Let us assume that we received the following text from a web server:

let obj = JSON.parse('{ "name":"David", "age":30, "city":"New York"}');
console.log(obj.city);

Output

New York

Example 2: Passing a reviver function

let jsonString = '{"name":"David", "age":30, "city":"New York"}';
let obj = JSON.parse(jsonString, (key, value) => {
 if (key === "name") {
 return value;
 }
 return value;
});

console.log(obj.name + " "+ obj.age);

Output

David 30

Browser Compatibility

  • Google Chrome 3 and above
  • Edge 12 and above
  • Firefox 3.5 and above
  • Safari 4 and above
  • Opera 10.5 and above

1 thought on “JavaScript JSON parse() Method”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.