How to Convert Object to String and String to Object in Javascript?

How to Convert Object to String and String to Object in Javascript?

In this Javascript Tutorial, I will let you know how to converts Javascript object into strings and string into json object.

The JSON.stringify() method is used to convert JSON Object into JSON string. Sometimes in the development, we need to serialize the data to strings in order to interact with APIs or web server.

The JSON.parse() method is used to convert JSON string into JSON object. Sometimes you send json string to APIs or web server and on the web server side you need to convert that string to valid json object to read parameters. This conversion of an string to object can be easily done with the help of the JSON.parse() method.

Below is an example of converting object to string and string to object back :

<!DOCTYPE html>
<html>
<head>
    <title>How to Convert Object to String and String to Object in Javascript? - expertphp.in</title>
</head>
<body>
  
<script>
      
    var obj = {
        url: "http://www.expertphp.in/"
    };
  
    var stringObj = JSON.stringify(obj);
  
    console.log(typeof stringObj); // string

    var jsonObj=JSON.parse(stringObj)

    console.log(typeof jsonObj); // object
  
</script>
  
</body>
</html>

In above example, I have defined a simple object and then I convert them into string using JSON.stringify method. Again I convert that json string into an object with the help of JSON.parse() method.

Phone: (+91) 8800417876
Noida, 201301