I've been getting an 'Invalid JSON' after making a jQuery AJAX Request. This request code is not important, so i have chosen to omit it.
I've delved into the jQuery library and stripped out the relevant code, which is aggregated into the snippet below.
So, given that my request returns a string "{'x':'1'}", why should during the course of processing it, jQuery return "{'x':']'}" ?
//regex values stripped from jQuery 1.5.2.
var data = "{'x':'1'}";
var rvalidchars = /^[\],:{}\s]*$/;
var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
//test the various stages of data.replace from the jQuery library
alert (data.replace(rvalidescape, "@")); // {'x':'1'}"
alert (data.replace(rvalidescape, "@").replace(rvalidtokens, "]")); //{'x':']'}"
alert (data.replace(rvalidescape, "@").replace(rvalidtokens, "]").replace(rvalidbraces, "")); //{'x':']'}"
You can see it at this JSFiddle
Moreoever, the following conversions happen:
'{x:12}' --> '{x:]}'
'{"x":"12"}' --> '{],]}'
I'm guessing someone could explain to me why the regex does this, but I'm also curious as to why jQuery does it.
Any help would be much appreciated