Search code examples
javascriptjsondefaultoverridingstringify

How to ignore .toJSON function when using JSON.stringify()?


I found out that if you define .toJSON() function for an object, then it's used to stringify an object, rather than default. Is there a way to ignore this overridden function and run the default stringify process?


Solution

  • Redefine the toJSON method in the specified object. For example:

        function kryptonite(key)
           {
           var replacement = {};
           for(var __ in this)
             {
             if(__ in alias)
               replacement[__] = this[__]
             }
        
           return replacement;
           }
        
        var foo, bar;
        var alias = {"Clark":"","phone":""};
        var contact = {
                       "Clark":"Kent",
                       "Kal El":"Superman",
                       "phone":"555-7777"
                      }
        
        contact.toJSON = kryptonite;
    
        foo = JSON.stringify(contact);
    
        contact.toJSON = undefined;
        
        bar = JSON.stringify(contact);
    
        console.log("foo: ", foo);
        console.log("bar: ", bar);

    References