0

I'm new to javascript and JSON and I've been given a task to complete. Please find the JSON in the following link,

http://pastebin.com/0BY3eptF

According to me the above is a very complex JSON.

I'm trying to fetch the out from a WSDL via ajax

success: function(api) {
    console.log(api.SearchResult); // trying to fetch information on SearchResult object
}

This doesn't work. I would like to learn how to iterate each JSON string loop. I also see an array which is WSResult[]. A neat javascript with explanation will help me a lot. Thank you.

Ashik Basheer
  • 1,531
  • 3
  • 16
  • 36

3 Answers3

1

success: function(api) {}, here, api is still a string, you have to parse it to JSON first:

success: function(api) {
    var api = JSON.parse(api);
    console.log(api.SearchResult); // trying to fetch information on SearchResult object
}
wong2
  • 34,358
  • 48
  • 134
  • 179
  • It's not a string if you've set dataType to JSON in the AJAX call. It should also infer this if using jQuery – vogomatix Apr 21 '14 at 10:08
1

Some web services return content type as plain text instead of json, you have to manually convert into json. below code will help you do the same.

success: function(api) {
    if (api.constructor === String) {
        api = JSON.parse(api);
    }
    console.log(api.SearchResult);
}

To loop through api.SearchResult.Result.WSResult array, please find below code

$(api.SearchResult.Result.WSResult).each(function (index, val) {
    // here val is single object of WSResult array
});
  • Alternatively I believe explicitly specifying the dataType would ensure JQuery handles all this for you.... – vogomatix Apr 21 '14 at 10:20
1

Not a complete answer, but some useful pointers:

$ajax({
    url: 'http://myURL',
    // specify the datatype; I think it overrides inferring it from the document MIME type
    dataType: 'json', 
    success: function (api) {
        // provided your data does come back as a JSON document
        // you should be able to access api.SearchResult
    },
    error: function( jsXHR, textStatus, errorThrown) {
        // always have an error handler, so you can see how it went wrong.
    }
);

Read the section on dataType here, as it may solve your problem

vogomatix
  • 4,856
  • 2
  • 23
  • 46