In this article, I show you how to convert JSON to string in JavaScript and which method you can use to convert JSON objects to string.
JSON to string
In JavaScript, you can convert a JSON object to a string using the JSON.stringify() method. This method takes the JSON object as an argument and returns a string representation of the object.
For example, suppose you have a JSON object like below –
let jsonObject = { "name": "John Doe", "age": 30, "address": { "street": "123 Main St", "city": "New york", "state": "New york" }, "country": "US", };
You can convert this JSON object to a string using the JSON.stringify() method like the below –
let jsonString = JSON.stringify(jsonObject); console.log(jsonString);
Output –
{"name":"John Doe","age":30," address":{"street":"123 Main St","city":"New york","state":"New york"},"country":"US"}
As you can see, the JSON.stringify() method takes the JSON object and converts it to a string that is a valid JSON representation of the object.
You can also use the second and third parameters of JSON.stringify() to customize the output, the second parameter is a replacer function that can be used to filter out values, change the data, or add white space. The third parameter is a number or string to be used as white space that can be used to format the output.
Note – The third parameter is from 0 to 10, to indicate how many space characters to use as white space.
let jsonString = JSON.stringify(jsonObject,null,2); console.log(jsonString);
And below is the Output –
{ "name": "John Doe", "age": 30, "address": { "street": "123 Main St", "city": "New York", "state": "New York" }, "country": "US" }
Here the third parameter 2 is used to format the output with 2 spaces of indentation.
Key Point When Converting JSON to string
So, When you convert a JSON object to a string using the JSON.stringify() method, Below are a few key points to keep in mind-
- The JSON.stringify() method takes the JSON object as the first argument and returns a string representation of the object.
- The second parameter is the replacer function, which can be used to filter out or modify values before they are stringified.
- The third parameter is the number of spaces to use for indentation, which can be used to format the output.
- The JSON.stringify() method will convert all non-string values to strings, including numbers, Boolean values, and null.
- The JSON.stringify() method will ignore any properties in an object that have the value undefined or are non-enumerable.
Conclusion
I hope now will be able to effectively convert JSON objects to strings and customize the output using the JSON.stringify() method. This is how JSON to string works using JSON.stringify() method.