#StackBounty: #javascript #json #parsing JSON.parse overwrite to handle passing in objects

Bounty: 50

I have a legacy system I’m maintaining. We are in the process of setting JSON response content to "application/json" (from "text/plain"). Since the responses were interpreted as plain text before there is a fairly substantial number of places where the code calls JSON.parse. We found that when we make the change, the parsing breaks since the response is now interpreted as a JSON object, which cannot be passed to JSON.parse without an error.

Now the obvious solution is to go in and properly fix all these in coordination with the back-end changes, but it’s A LOT. As a stop-gap measure and to make sure nothing gets broken, I’d like to add the following code. The idea is, if the passed input is already an object it simply gets returned. Anything else goes to the proper JSON.parse.

  //handle loose JSON parsing
  JSON.strictParse = JSON.parse;
  JSON.parse = function (input, reviver) {
    if (typeof input == "object") return input;
       return JSON.strictParse(input, reviver);
  }

My question is, is this a terrible idea, and if so why? The only thing I can think of is if some library somehow relied on the original behaviour, but that seems fairly far fetched.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.