json 

Send to Kindle
home » snippets » javascript » json



On JSON.stringify

Ref:  stringify(value[, replacer [, space]])

Example:

JSON.stringify({
    foo: function() {},
    arr: [function bar() {}, undefined, new String("strobj")]
});

Output

{"arr":[null,null,"strobj"]}

replacer parameter to JSON.stringify

Refer MDN: replacer parameter

The replacer parameter is either a function OR an array. As a function, it has the properties:

reviver parameter to JSON.parse

Refer MDN: reviver parameter

The parsed JS object and all it's properties are recursively (starting from the most nested) transformed using the reviver to reconstruct the final object.

Sample reviver snippet

function _prefixAllKeys(obj, prefix) {
  if (obj instanceof Object && Object.getPrototypeOf(obj) === Object.prototype) {
    var result = {};
    for (var k of Object.keys(obj)) {
      result[prefix + k] = obj[k];
    }
    return result;
  } else {
    return obj;
  }
}

function jsonReviver(key, obj) {
  return _prefixAllKeys(obj, "ckck_");
}

var o1 = {
  a: [1, 2],
  b: { c: 1}
};

var json = JSON.stringify(o1);

// logs: { ckck_a: [ 1, 2 ], ckck_b: { ckck_c: 1 } }
console.log(JSON.parse(json, jsonReviver));