Search code examples
javascriptjson

How to get JSON from URL in JavaScript?


This URL returns JSON:

{
  query: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  }
}

I tried this, and it didn't work:

responseObj = readJsonFromUrl('http://query.yahooapis.com/v1/publ...');
var count = responseObj.query.count;

console.log(count) // should be 1

How can I get a JavaScript object from this URL's JSON response?


Solution

  • You can use jQuery .getJSON() function:

    $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
        // JSON result in `data` variable
    });
    

    If you don't want to use jQuery you should look at this answer for pure JS solution.