jqueryajaxjavascriptjson

How to parse json response for ajax request?


I am newbie to ajax/javascript. I am trying to parse a response for this ajax request:

function invokeMediationRestService(rql) {
    var resourceinfo;
    var request = $
        .ajax({
            type : "POST",
            url : "REST_URL",
            async : false,
            data : 'SOME_DATA',
            contentType : "application/xml",
            dataType : "xml",
            success: function(response) {
            }
        });
            
    return resourceinfo;
}    

For this request I am expecting a response like the JSON below:

{
    "xml-fragment": {
      "@payloadMode": "JSON",
      "serializedPayload": "{\"items\":[{\"$param\":\"Response\",\"mode\":\"OUT\",\"$value\":[{\"resource\":[{\"firstName\":\"abc\",\"email\":\"abc2.klm@xyz.com\",\"alias\":\"cklm28\",\"manager\":\"vbu\",\"location\":\"qwerty\",\"department\":\"asdfg\",\"lastName\":\"klm\",\"displayName\":\"klm, abc\",\"containerID\":\"456\",\"containerName\":\"sfdghjjk\",\"groupID\":{\"guid\":\"23454356wert\",\"name\":\"qweryugg\",\"label\":\"asdfgfdg\",\"$type\":\"sdfgdsf\"},\"$type\":\"sdfgsdfg\"},{\"firstName\":\"abc\",\"email\":\"abc3.klm@xyz.com\",\"alias\":\"cklm29\",\"manager\":\"sdfgrt\",\"location\":\"qwerty\",\"department\":\"sdfghj\",\"lastName\":\"klm\",\"displayName\":\"klm, abc (zxa2)\",\"containerID\":\"456\",\"containerName\":\"sfdghjjk\",\"groupID\":{\"guid\":\"23454356wert\",\"name\":\"qweryugg\",\"label\":\"dfgh\",\"$type\":\"dghdh\"},\"$type\":\"dfghgfh\"}]},{\"$param\":\"dfghj\",\"$value\":[\"sdfghj\"],\"type\":\"String\",\"mode\":\"IN\"}]}"
    }
}

Please note: There are multiple records under items[0].$value[0].resource. I want to extract these records and return them.

Can anyone please help?

Thanks, Ranjeet


Solution

  • It'll probably be a little trial and error - I get a bit confused with JSON at times and forget which sections are arrays and which are just readable.

    When I've been dealing with JSON before I use

    var json = JSON.parse(JSON.stringify(data));
    

    to get the parsed object. You can then access key/value pairs with something like json.items. If there can be multiple items I think you would want something like json.items[0].$value[0].resource[0].name to read from the right section, but depending on how flexible the layout of your JSON response is you might need to specify the index (using [index]) at other points.