简体   繁体   中英

How to parse json response for ajax request?

I am newbie to ajax/javascript. I am trying to parse response for below 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 response like below: JSON:

{ "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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM