How to Convert JS Object to JSON String?
Answer: Using JSON.stringify()
method
We can convert the JavaScript object or value into the JSON string using JSON.stringify() method.
The difference between the JSON object and the JavaScript object is that in JSON string, all the keys and string type values are wrapped in double quotes (""). While in the JavaScript object, we don't have to wrap the keys and strings within the double-quotes. We can even use single quotes for strings, and there is no need to use any quotation marks for the keys.
To get the valid string of JSON, we have to pass the JavaScript object to the JSON method.
Example: Using JSON.stringify()
method
In the given example, we have used the JSON.stringify()
method to convert the JavaScript object named empDetails into the JSON string.
<!DOCTYPE html>
<html lang="en">
<head>
<title> Convert JS Object to JSON String</title>
</head>
<script>
var empDetails = {name: "Henry", age: 32, department: "Management"};
var jsonStr = JSON.stringify(empDetails);
console.log(jsonStr);
</script>
</body>
</html>
Output
{"name":"Henry","age":32,"department":"Management"}
So we have learned how to convert the JavaScript object into the JSON string but what if we want to convert the JSON string into the JavaScript object. To convert the JSON string into the JavaScript object, we have to use the JSON.parse()
method.
This method converts the JSON string into the JavaScript object; we just have to pass the JSON string into the JSON.parse()
method.
Example: Using JSON.parse()
method
In the given example, we have converted the JSON string into the JavaScript object using the JSON.parse()
method.
<!DOCTYPE html>
<html lang="en">
<head>
<title> Convert JS Object to JSON String</title>
</head>
<script>
var empDetails = '{"name":"Henry","age":32,"department":"Management"}';
var jsonStr = JSON.parse(empDetails);
console.log(jsonStr);
</script>
</body>
</html>
Output
{name: "Henry", age: 32, department: "Management"}
Conclusion
In this lesson, we have discussed how to convert the JavaScript object into the JSON string. So, we can convert the JS objects into JSON strings using JSON.stringify() method. We just have to pass the JavaScript object into the JSON.stringify()
method. To convert the JSON string into the JavaScript object, use the JSON.parse()
method.