Convert JSON String into JavaScript Object

In this tutorial, we are going to learn about how to convert a JSON string into JavaScript object with an example.
Learn more about JavaScript at https://www.javaguides.net/p/javascript-tutorial-with-examples.html

Usiing JSON.parse() Method

The JSON.parse() method parses a string and returns a JavaScript object. 

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 in the above example, we are passing JSON string to JSON.parse() method which returns JavaScript Object.

JSON.parse() Method - Detail Explanation

The JSON.parse() method parses a string and returns a JavaScript object. 

Syntax

JSON.parse(text[, reviver])

Parameter Values

  • text - This is a required field. A string is written in JSON format
  • reviver function - This parameter an optional. A function used to transform the result.
An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

JSON.parse() Method Examples

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 the 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

Convert a JavaScript Object to JSON String

References

Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments