tags:

views:

38

answers:

1

I have a simple getJson request:

$.getJSON('JsonTest', function(o) {
alert(o.Test);
});

It works, but in Firebug the "o" never gets turned into an object, but stays a string:

{"Test":"Hello"}

If I do an

eval('(' + o + ')')

It gets evaluated fine, the only thing I can think of is that there's some sort of cross site scripting problem, but I'm running everything on my development machine, the JsonTest is off of localhost:port/Controller/JsonTest

Any ideas as to what could be wrong? How do I check to see whether or not it is a cross site issue? Any other ideas?

+2  A: 

Is it possible that your JsonTest service is "double escaping" the json that gets sent back? As in:

"{\"Test\":\"Hello\"}"

Since you have firebug, can you take a look at the response and paste the raw text that it shows?

If your service method returns a string, and you are doing your own serialization, then this is definitely the case. I ran in to this recently. Anyway, with the "double quoted" (or double wrapped, double escaped, whatever you want to call it) json coming back, $.getJSON() only eval()'s it once, turning "{\"Test\":\"Hello\"}" into {"Test":"Hello"}, which does indeed still require an additional eval().

Also, don't use eval(). Use JSON.parse(). You can include json2.js from http://json.org/, and JSON.parse() will either use the browser's native json parsing abilities, or fall back on json2.js if the browser doesn't do it natively.

Samuel Meacham
@Reigel: Thanks for the heads up on the change.
Samuel Meacham
You're right! Oh my God all afternoon on this! I was doing a Public JsonResult() ... return Json(TestJson) ... and in between was serializing by hand (long story), so when I called Json it would serialize again. Wow, all afternoon on this. This explains why my other JsonResults were working fine. Wow, thanks again.
chum of chance
You're lucky you only spent *1* afternoon on it, haha. I think it took me 2 ;-)
Samuel Meacham