0

I just created a function that return JSON.stringify like this:

JSON.stringify = function (item, replacer, space) {
     return JSON.stringify(item, replacer, space);
}

and it causes all these errors on angularjs: click here

The reason I want to override the function is because I want to create a property in objects that tells the JSON to ignore a field, like this:

JSON.stringify = function (item, replacer, space) {
    if (angular.isObject(item)) {
        var newItem = angular.copy(item);
        var ignores = item.jsonIgnore || [];

        ignores.forEach(prop => {
            delete newItem[prop];
        });

        return JSON.stringify(newItem, replacer, space);
    }

    return JSON.stringify(item, replacer, space);
}
Eduardo Rosostolato
  • 742
  • 1
  • 8
  • 21

2 Answers2

0

It is a recursive function without any end condition. Either you can solve the problem with creating a local function:

var localStringify = function (item, replacer, space) {
    ...
}

Or override the original function considering the explanation given in this thread.

Pedram
  • 828
  • 9
  • 24
0

Thanks all, I resolved creating a local variable with the original function

var originalStringify = JSON.stringify;

and then calling on my custom function

return originalStringify(item, replacer, space);

Now my full Json ignore override function is like this:

// JSON ignore
var original = JSON.stringify;

JSON.stringify = function (item, replacer, space) {
    if (angular.isObject(item)) {
        var newItem = angular.copy(item);
        var ignores = item.jsonIgnore || [];

        ignores.forEach(prop => {
            delete newItem[prop];
            delete newItem.jsonIgnore;
        });

        return original(newItem, replacer, space);
    }

    return original(item, replacer, space);
}
Eduardo Rosostolato
  • 742
  • 1
  • 8
  • 21