0

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

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the advice. Think I must be doing something stupid. It all works fine with the correctly formed JSON.
Quoted jquery logic was inspired by cdnjs.cloudflare.com/ajax/libs/json2/20130526/json2.js
1

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

you must use double quotes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.