JSON stringify()

The JSON.stringify() function, as name suggests, converts a JavaScript value to a serialized JSON string. JSON.stringify() can optionally use a replacer function to replace values using custom logic. 1. Syntax The syntax of the JSON.stringify() method is: 1.1. Method Parameters 2. JSON.stringify() Example Program output. 3. JSON.stringify() Replacer …

The JSON.stringify() function, as name suggests, converts a JavaScript value to a serialized JSON string.

JSON.stringify() can optionally use a replacer function to replace values using custom logic.

1. Syntax

The syntax of the JSON.stringify() method is:

JSON.stringify(value[, replacer[, space]])

1.1. Method Parameters

  1. value (required) – The JavaScript object which needs to be converted to a JSON string.
  2. replacer (optional) – The function that alters the behavior of the stringification process. If replace function is not provided, all properties of the object are included in the resulting JSON string.
  3. space (optional) – For indentation purpose. A String or Number that’s used to insert whitespaces into the output JSON string for readability purposes.

    If this is a Number, it indicates the number of space characters to use as whitespace.

2. JSON.stringify() Example

console.log( JSON.stringify({ x: 5, y: 6 }) );
console.log( JSON.stringify({ x: 5, y: 6 }, null, ' ') ); //with space

Program output.

{"x":5,"y":6}

{
"x": 5,
"y": 6
}

3. JSON.stringify() Replacer Function Example

var unmaskedData = { "name":"Lokesh", "accountNumber":"3044444444", "city":"New York"};

var maskedData = JSON.stringify( unmaskedData, maskInfo );

function maskInfo (key, value) {
	var maskedValue = value;
	if (key == "accountNumber")
	{
		if(value && value.length > 5) {
			maskedValue = "*" + maskedValue.substring(value.length - 4, value.length);
		} else {
			maskedValue = "****";
		}
	}
	return maskedValue;
}

Program output.

{
"name": "Lokesh",
"accountNumber": "*4444", //Masked account number
"city": "New York"
}

Read More: Replacer function usage

4. Handling undefined values

JSON.stringify() does one of the following with an undefined value:

  • Omits the value if it’s part of an Object
  • Converts the value to null if that value belongs to an Array

In the given example, name is omitted from serialized JSON. Also, the undefined in the array admins is converted to null.

var siteInfo = {
"name" : undefined,
"users" : [
		[ "admins", "1", "2" , undefined],
		[ "editors", "4", "5" , "6"],
	]
}

console.log( JSON.stringify(siteInfo) );

Program output.

{"users":[ ["admins","1","2",null], ["editors","4","5","6"] ]}

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments