The Javascript JSON.stringify()
method converts a JavaScript to a JSON string.
If value has toJSON()
method it will call it.
JSON.stringify(value[, replacer[, space]])
let a = JSON.stringify({}); console.log(a);// '{}' a = JSON.stringify(true);//from www . ja va2 s . c o m console.log(a);// 'true' a = JSON.stringify('foo'); console.log(a);// '"foo"' a = JSON.stringify([1, 'false', false]); console.log(a);// '[1,"false",false]' a = JSON.stringify([NaN, null, Infinity]); console.log(a);// '[null,null,null]' a = JSON.stringify({ x: 5 }); console.log(a);// '{"x":5}' a = JSON.stringify(new Date(2020, 0, 2, 15, 4, 5)) console.log(a); // '"2020-01-02T15:04:05.000Z"' a = JSON.stringify({ x: 5, y: 6 }); console.log(a);// '{"x":5,"y":6}' a = JSON.stringify([new Number(3), new String('false'), new Boolean(false)]); console.log(a); // '[3,"false",false]'
If value has toJSON()
method it will call it.
let a= JSON.stringify({ x: 5, y: 6, toJSON(){ return this.x + this.y; } }); console.log(a);// '11'
The replacer parameter can be either a function or an array.
For a function, it takes two parameters:
function replacer(key, value) { if (typeof value === 'string') { return undefined;//remove }/*from w w w . ja v a 2s. c o m*/ return value; } var foo = { lang : 'CSS', model: 'client', hours: 45, date: 7 }; let a = JSON.stringify(foo, replacer); console.log(a);
If replacer is an array, it indicates the names of the properties to include in the resulting JSON string.
var foo = {/*from w ww .j a va 2 s.c o m*/ lang : 'CSS', model: 'client', hours: 45, date: 7 }; let a = JSON.stringify(foo, ['lang', 'date']); console.log(a);
The space argument can control spacing in the string returned.
let a = JSON.stringify({ a: 2 }, null, ' '); console.log(a);
Using a tab character mimics standard pretty-print appearance:
let a = JSON.stringify({ id: 1, value: 2 }, null, '\t'); console.log(a);