środa, 22 kwietnia 2020

JSON stringify - transformation tip

JSON stringify


Well known JavaScript method for transforming objects or values into string. However, there is an optional second parameter to the call - a replacer. Once provided, alters the stringification process.

Method

If a method is provided, will be applied to each property of an object. Very handy tool if serialised form has to have for example different values. For example:


let data = {'one' : 1, 'two' : 'a string'};
JSON.stringify(data, (key, value) => key === 'one' ? 2 : value)
// "{"one":2,"two":"a string"}"


As the object being serialized is also available (as this reference), we may perform a wider range of transformations, for example:


data = {x : 1, y : 2, multiplier : 10};
function replacer(key, value) {return typeof value === 'number' ? value * this.multiplier : value}
JSON.stringify(data, replacer);
// "{"x":10,"y":20,"multiplier":100}"

Array

Simply put - a whitelist. Only selected properties will appear in the serialised form. For example:


let data = {'one' : 1, 'two' : 'a string', 'garbage' : 'some'};
JSON.stringify(data, ['one' ,'two']);
// "{"one":1,"two":"a string"}"


To sum up - a very handy tool for quick-and-dirty processing of a bare JSON / JS objects.