Getting JSON data from url in javascript?

I am trying to extract data from the form url http://www.xyz.com/abc.json . I tried to achieve this using the $ .ajax method as follows.

    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 can't seem to get this to work. I need to go through the received data and check some specific conditions. This could easily have been achieved with $ .getJSon if the json data had a name for it, however the file looks like:

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

      

due to which I have to efficiently convert and store it in a Javascript object variable before I can use it. Any suggestions on where I might go wrong?

+3


source to share


2 answers


It sounds like you want to convert this response data

to a json object by wrapping it {

}

and then passing it to a json parser.

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

      



Then, to get your data, it would be

json[0].name  //"abc"

      

+1


source


So your question is how to convert a string to a 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 the documentation here

0


source







All Articles