Mutation Person
Mutation Person

Reputation: 30498

Regex Bafflement in jQuery (1.5.2)

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

Upvotes: 0

Views: 217

Answers (2)

Gijs
Gijs

Reputation: 5262

From the looks of it, jQuery is replacing anything that isn't a valid JSON token with ']'. Some things, like 'null', 'true', 'false', etc. can be inserted without quotations. In fact, numbers can, too!

Your JSON is not valid because you need to double-quote values. So either:

{"x": 1}

or

{"x": "1"}

should work. Your copied code still mangles this, but throwing it through jQuery.parseJSON() works fine for me.

Upvotes: 2

BiAiB
BiAiB

Reputation: 14122

your JSON string is malformed according to : http://api.jquery.com/jQuery.parseJSON/

you must use double quotes

Upvotes: 1

Related Questions