I am returning an “Employee” object from my javascript ajax call..
var xhReq = new XMLHttpRequest();
xhReq.open("POST", "MobileClientService.svc/REST/TestReturnEmployee", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
What is returned is JSON data. I would like to return an Object that has the structure of my Employee object so I could write in javascript..
var name = serverResponse.Name;
Is this possible to do or is my only choise to parse the returned JSON string? No I cant use jquery (it returns the object fine that way) it must be javascript only.
jQuery automatically parses the
responseTextinto an object when it expects a JSON response.In vanilla JS, you can parse it with
JSON.parse:Include this library also if you need compatibility with IE<=7: Crockford’s JSON2
About
evalIt’s also possible to use
evalto parse theresponseTextstring into an object to have compatibility with IE<=7 as well without including extra code, butevalis evil.Of course, if your server always echoes well-formed JSON, it wouldn’t be a problem. I’d personally avoid
evaland use the properJSON.parse, but if you want to useevalfor the IE<=7 compatibility without including extra code you can do it as follows: