JAVA SCRIPT - Converting an Object to a Filtered/Transformed String with JSON - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript JAVA SCRIPT - Converting an Object to a Filtered/Transformed String with JSON - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, January 3, 2019

JAVA SCRIPT - Converting an Object to a Filtered/Transformed String with JSON

Converting an Object to a Filtered/Transformed String with JSON


Problem

You need to convert a JavaScript object to a JSON-formatted string for posting to a web application. However, the web application has data requirements that differ from your client application.

Solution

Use the JSON.stringify() method, passing in the object as first parameter and pro‐ viding a transforming function (a replacer) as the second parameter:
function convertBoolToNums(key, value) {
 if (typeof value == 'boolean') {
 if (value)
 value = 1;
 else
 value = 0;
 }
 return value;
};
var obj = {test : "value1",
 test2 : 3.44,
 test3 : false};
var jsonstr = JSON.stringify(obj, convertBoolToNums, 3);
console.log(jsonstr); // '{ "test" : "value1", "test2" : 3.44, "test3" : 0}'

EXPLAIN

The JSON.stringify() method takes three parameters: the object to be transformed into JSON, an optional function or array used either to transform or filter one or more object values, and an optional third parameter that defines how much and what kind of whitespace is used in the generated result. In the solution, a function is used to check property values, and if the value is a Boolean, converts false to 0, and true to 1. 

The function results are transformed into a string if the return value is a number or Boolean. The function can also act as a filter: if the returned value from the function is null, the property/value pair is removed from the JSON.

You can also use an array rather than a function. The array can contain strings or num‐ bers, and is a whitelist of properties that are allowed in the result. The following code:



var whitelist = ["test","test2"];
var obj = {"test" : "value1", "test2" : 3.44, "test3" : false};
var jsonobj = JSON.stringify(obj, whitelist, '\t');
Would result in a JSON string including the object’s test and test2 properties, but not the third property (test3), The resulting string is also pretty-printed using a tab (\t) this time, instead of the three spaces used in the solution:
{
 "test": "value1",
 "test2": 3.44
}

The last parameter controls how much whitespace is used in the result. It can be a number representing the number of spaces or a string. If it is a string, the first 10 char‐ acters are used as whitespace. If I use the following:

var jsonobj = JSON.stringify(obj, whitelist, "***");

the result is:

{
***"test": "value1",
***"test2": 3.44
}

No comments:

Post a Comment

Post Top Ad