7

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?

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335
  • I suppose if you really wanted to override toJSON but still wanted to run the default stringify, you could iterate over they object and print the keys? You would be pretty much implementing stringify on your own though – Danny Sullivan Jun 29 '15 at 12:27
  • The issue is - I use a 3rd party library from Parse.com service that works with its objects. Now I need to get an original representation of an object that is uses so that to pass it as a mock object to my unit tests. But that library defines its .toJSON() function which I want to ignore for test purpose. – Sergei Basharov Jun 29 '15 at 12:35
  • If it's for debugging purposes, can you use console.log(obj)? – Danny Sullivan Jun 29 '15 at 12:47
  • Yes, I can see it as a tree in Chrome console, but I can't copy and paste it as a string. I tried this trick http://superuser.com/questions/777213/copy-json-from-console-log-in-developer-tool-to-clipboard, but it seems to handle it with the same approach, so I get the result that is processed with .toJSON() – Sergei Basharov Jun 29 '15 at 12:52
  • Ugly hack: `obj.toJSON = undefined` – robertklep Jun 29 '15 at 12:53
  • Robert, please put it as an answer, it worked, thanks! – Sergei Basharov Jun 29 '15 at 13:32

1 Answers1

0

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

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265