A JavaScript object can be converted into a JSON string using JavaScript's built-in JSON.stringify() method. This is useful when storing, transmitting, or sending object data through APIs.
Note: jQuery does not provide a separate method for converting a JavaScript object into a JSON string. The conversion is performed using JavaScript's JSON.stringify() method.
[Approach 1]: Using the JSON.stringify() Method
The JSON.stringify() method converts a JavaScript object or array into a JSON-formatted string.
- Create a JavaScript object.
- Pass the object to JSON.stringify().
- Store or use the returned JSON string.
Syntax:
JSON.stringify(value)Example: Converts a JavaScript object into a JSON string.
const geeks = {
name: "Lucas",
age: 21,
intern: "GeeksforGeeks",
place: "Work from Home"
};
const jsonString = JSON.stringify(geeks);
console.log(jsonString);
Output
{"name":"Lucas","age":21,"intern":"GeeksforGeeks","place":"Work from Home"}
[Approach 2]: Using JSON.stringify() with Formatting
The JSON.stringify() method can also format the JSON string to make it easier to read.
- The first argument is the value to convert.
- The second argument can be used as a replacer.
- The third argument specifies the indentation level.
Syntax:
JSON.stringify(value, replacer, space)Example: Converts a JavaScript object into a formatted JSON string.
const geeks = {
name: "Lucas",
age: 21,
intern: "GeeksforGeeks",
place: "Work from Home"
};
const jsonString = JSON.stringify(
geeks,
null,
2
);
console.log(jsonString);
Output
{
"name": "Lucas",
"age": 21,
"intern": "GeeksforGeeks",
"place": "Work from Home"
}
[Approach 3]: Using JSON.stringify() with jQuery
When working in a project that uses jQuery, JavaScript's JSON.stringify() method can still be used to convert an object into a JSON string. jQuery can then be used to display the result on the webpage.
Example: Converts a JavaScript object into a JSON string and displays it using jQuery.
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Convert JavaScript Object to JSON String
</title>
<script src=
"https://code.jquery.com/jquery-3.7.1.min.js">
</script>
</head>
<body>
<h2>
Convert JavaScript Object to JSON String
</h2>
<button id="convertButton">
Convert to JSON
</button>
<pre id="output"></pre>
<script>
$("#convertButton").click(function () {
const geeks = {
name: "Lucas",
age: 21,
intern: "GeeksforGeeks",
place: "Work from Home"
};
const jsonString =
JSON.stringify(geeks, null, 2);
$("#output").text(jsonString);
});
</script>
</body>
</html>
Output: