Convert Object or Value to JSON String
JSON
The JSON is an inbuilt object provided by javascript. This contains methods for parsing a JSON string into an object or converting it to JSON serialized string.
JSON.stringify()
This stringify method is used to create a serialized string.
Syntax
JavaScript1JSON.stringify(value, replacer, space)
Parameters
<u>value</u>
The value can be an object, an array, a number, a string, a boolean, or null. The input value gets converted into a serialized string.
Here are some examples using JSON.stringify:
JavaScript1JSON.stringify({}); // Output => '{}' 2JSON.stringify(true); // Output => 'true' 3JSON.stringify('foo'); // Output => '"foo"' 4JSON.stringify([1, 'false', false]); // Output => '[1,"false",false]' 5JSON.stringify([NaN, null, Infinity]); // Output => '[null,null,null]' 6JSON.stringify({ x: 5 }); // Output => '{"x":5}'
If a JavaScript object has a toJSON() method, then that method is responsible for serialized data conversion.
JavaScript1const person = { 2 name: 'John', 3 age: 20, 4 gender: 'male', 5 toJSON: function() { 6 return { 7 name: this.name, 8 age: this.age, 9 }; 10 } 11}; 12 13JSON.stringify(person); // Output => '{"name":"John","age":20}'
The undefined, function, and symbol are not valid JSON values. Such values are omitted when found in an object or converted to null when found in an array.
JavaScript1const person = { 2 first_name: 'John', 3 last_name: 'Doe', 4 age: undefined, 5 getFullName: function() { 6 return `${this.first_name} ${this.last_name}`; 7 }, 8 id: Symbol(), 9}; 10 11JSON.stringify(person); // Output => '{"first_name":"John","last_name":"Doe"}' 12JSON.stringify([undefined, function getFullName() {}, Symbol()]); // Output => '[null,null,null]'
The JSON.stringify method returns undefined if a pure non-valid JSON value is passed.
JavaScript1JSON.stringify(undefined); // Output => undefined 2JSON.stringify(function getFullName() {}); // Output => undefined 3JSON.stringify(Symbol()); // Output => undefined
The numbers Infinity and NaN, as well as the value null, are all converted to null.
JavaScript1JSON.stringify(Infinity); // Output => 'null' 2JSON.stringify(NaN); // Output => 'null' 3JSON.stringify(null); // Output => 'null'
The non-enumerable properties of an object will not be serialized.
JavaScript1const abObject = { 2 a: { value: '1', enumerable: false }, 3 b: { value: '2', enumerable: true } 4}; 5 6JSON.stringify(Object.create(null, abObject)); // Output => '{"b":"2"}'
<u>replacer</u> - Optional
The replacer can be a function or an array of strings and numbers to allow properties of an object.
Here is an example of a function as a replacer:
JavaScript1function replacer(key, value) { 2 if (typeof value === 'string') { 3 return undefined; 4 } 5 return value; 6} 7 8const obj = { name: 'John', age: 21 }; 9JSON.stringify(obj, replacer); // Output => '{"age":21}'
Here is an example of properties allow list as a replacer:
JavaScript1const obj = { name: 'John', age: 21 }; 2JSON.stringify(obj, ['age']); // Output => '{"age":21}'
<u>space</u> - Optional
The space argument is used to control spacing in the final serialized string.
JavaScript1const obj = { name: 'John', age: 21 }; 2JSON.stringify(obj, ['age'], ' '); // Output => '{ "age":21 }'
Errors Conditions
<ol> <li>The JSON.stringify() throws an error if the length of the serialized string is more than the max string length supported by the JavaScript engine.</li> <li>The JSON.stringify() throws TypeError when serializing circular references.</li> </ol>// Emit event eventEmitter.emit('account_created');
// Add event handlers eventEmitter.on('account_created', () => { // perform your action A }); eventEmitter.on('account_created', () => { // perform your action B });
// traditional function definition function calculateArea(height, width) { return height * width; }
// arrow function (height, width) => height * width;
// Easy routing in Laravel Route::get('foo', function () { return 'Hello World'; });
// Using controller Route::get('/user', 'UserController@getUser'); Route::post('/user', 'UserController@createUser');
// simple callback example var callback = function(response, status) { console.log('Executed after ajax response'); console.log(response, status); };
// Using the callback $.get('/some-url', callback); console.log('Executed before ajax response');
// callback hell var dealWithFinalResponse = function(data) { console.log(data); };
var callback3 = function(response3, status) { console.log('Final output we needed'); dealWithFinalResponse(response3); };
var callback2 = function(response2, status) { console.log('Executed after ajax response from second call'); console.log(response2, status); $.get('/some-url-3?id=' + response2.id, callback3); };
var callback1 = function(response1, status) { console.log('Executed after ajax response from first call'); console.log(response1, status); $.get('/some-url-3?id=' + response1.id, callback2); };
$.get('/some-url-1', callback1);
// Promise as alternative to callback hell var dealWithFinalResponse = function(data) { console.log(data); };
var promise1 = new Promise(function(resolve, reject) { $.get('/some-url-1', function(response) { resolve(response); }); });
promise1.then(function(response1) { var promise2 = new Promise(function(resolve, reject) { $.get('/some-url-2?id=' + response1.id, function(response) { console.log('Executed after ajax response from first call'); resolve(response); }); });
promise2.then(function(response2) { var promise3 = new Promise(function(resolve, reject) { $.get('/some-url-3?id=' + response2.id, function(response) { console.log('Executed after ajax response from second call'); resolve(response); }); });
promise3.then(function(response3) {
console.log('Final output we needed');
dealWithFinalResponse(response3);
});
}); });
// async function definition async function fn() { return 'I am async function'; }
fn().then(function(response) { console.log(response); // it prints 'I am async function' });
// async function returning promise async function fn() { return new Promise(function(resolve, reject) { resolve('I am async function'); }); }
fn().then(function(response) { console.log(response); // it prints 'I am async function' });
// async function error handling async function fn() { throw new Error('Its error message'); }
try { fn().then(function(response) { console.log(response); }); } catch(err) { console.log(err); }
// Function with multiple await async function fnWithMultipleAwait() { let result1 = await fn1(); let result2 = await fn2(); let result3 = await fn3(); return { 1: result1, 2: result2, 3: result3 }; }