JavaScript - How to Convert an Object to String and Vice Versa

Hello dev's, Toady I'll show you how to convert our object to string. Sometimes we need into run in a situation where we need to convert to our object into string. That's why my today's topic is about how we can easily convert our object into string in a pure javascript way.

Converting object to string

First we'll see the below code snippet

<html>
<head>
    <title>Convert an array into object in javascript - shouts.dev</title>
</head>
<body>
  
<script>
    let object = {
    	id 		: 1,
    	name 	: "Tanvir Ahmed",
    	email 	: "[email protected]",
    	phone 	: "+8801631102838",
    	website : "shouts.dev",
    };

    //our given object
    console.log(object);
   
	//converted string
   	let converted_string = JSON.stringify(object)
  	console.log(converted_string);

  	//back to our previous real object
  	console.log(JSON.parse(converted_string));
  
</script>
</body>
</html>

It'll produce the below output.

Object Converted to String and Vice Versa

Here what we'll do is, first we'll take an object element. And then we'll convert these object into string using JSON.stringify() method. It'll convert any object to string. For more info about JSON.stringify(), see here.

And for retrieving our main object from the converted string we use JSON.parse(). This is the first and convenient way of parse any string into object. For more info about JSON.parse() you can see here.

That's it for today. Hope you've enjoyed this tutorial. If you've any questions or face any difficulty, catch me in the comment section. Thanks for reading. 😊