Search code examples
jsonoverridingstringify

Overriding Json.stringify to use json-stringify-safe


I want to override JSON.stringify to use the json-stringify-safe module to avoid getting circular error.

Here is my code :

(function () {
    const getSerialize = require('json-stringify-safe');
    const stringifyCore = JSON.stringify;
    JSON.stringify = (obj, replacer, spaces, cycleReplacer) => {
        return stringifyCore.apply(this, [obj, getSerialize(replacer, cycleReplacer), spaces]);
    };
}());

I also tried :

const getSerialize = require('json-stringify-safe');

const stringifyCore = JSON.stringify;
JSON.stringify = function (obj, replacer, spaces, cycleReplacer) {
    return stringifyCore(obj, getSerialize(replacer, cycleReplacer), spaces);
};

I get an error :

Maximum call stack size exceeded

The solution eplanied here does not work for me.. Overriding JSON.stringify causing error

Any ideas?


Solution

  • Ooh Just figured out that I was not int the right file.. I was trying this on webpack.config.js (This is an AngularJS project). I moved it in my app.js file and it works.

    Here is my solution in App.js

    (function () {
        const {getSerialize} = require('json-stringify-safe');
        
        const stringifyCore = JSON.stringify;
        JSON.stringify = function (obj, replacer, spaces, cycleReplacer) {
            return stringifyCore(obj, getSerialize(replacer, cycleReplacer), spaces);
        };
    }());