3

I am trying to retrieve data from a URL of the form http://www.xyz.com/abc.json. I have been trying to achieve this using the $.ajax method in the following manner.

    var json = (function () {
        var json = null;
        $.ajax({
            'async': false,
            'global': false,
            'url': "http://www.xyz.com/abc.json.",
            'dataType': "json",
            'success': function (data) {
                json = data;
            }
        });
        return json;
    })();

However I am being unable to get this to run. I need to loop through the retrieved data and check for some specific conditions. This could have been achieved easily with the $.getJSon if the json data had a name to it, however the file is of the form:

    [{
        "name": "abc",
        "ID": 46 
    }]

because of which I have to effectively convert and store it in a Javascript object variable before I can use it. Any suggestions on where I might be going wrong?

0

2 Answers 2

1

It looks like you will want to convert that data response to a json object by wrapping it with { } and then passing that to the json parser.

function (data) {
  json = JSON.parse("{\"arr\":"+data+"}").arr;
}

Then to get your data, it would be

json[0].name  //"abc"
Sign up to request clarification or add additional context in comments.

1 Comment

I think you've made a good point of having to parse the data to make it back into a JSon object. The server still doesn't give me the desired data though. Trying to think of what might be the reason behind this.
0

So your question is how to convert a string to Json object? If you are using Jquery you can do:

jQuery.parseJSON( jsonString );

So your return should be:

return jQuery.parseJSON( json );

You can read documentation here

3 Comments

I wasn't aware of $.get been async. I'll remove my suggestion
The URL points to a JSon file. Its not a string. I don't think this approach will do the job.
Can you give us an example of the data returned by the ajax call? make a console.log(data) inside success function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.