How to print the content of an object in JavaScript ?

The JSON.stringify() method is used to print the JavaScript object. This method is used to allow to take a JavaScript object or Array and create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data in a database or for sending the data to an API or web server. The data has to be in the form of the strings. This conversion of an object to a string can be easily done with the help of the JSON.stringify() function.
Syntax:
JSON.stringify(value, replacer, space)
Example 1: This example converts the object to a string by simply traversing it and appending the object property and value to the string.
Javascript
let GFG_object = { prop_1: 'val_11', prop_2: 'val_12', prop_3: 'val_13'};let printObj = function (obj) { let string = ''; for (let prop in obj) { if (typeof obj[prop] == 'string') { string += prop + ': ' + obj[prop] + '; \n'; } else { string += prop + ': { \n' + print(obj[prop]) + '}'; } } return string;}console.log(printObj(GFG_object)); |
prop_1: val_11; prop_2: val_12; prop_3: val_13;
Example 2: This example using the JSON.stringify() method to convert the object to string.
Javascript
let GFG_object = { prop_1: 'val_11', prop_2: 'val_12', prop_3: 'val_13'}; console.log(JSON.stringify(GFG_object)); |
{"prop_1":"val_11","prop_2":"val_12","prop_3":"val_13"}



