244

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?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Yiğit Doğuş Özçelik
  • 2,763
  • 2
  • 16
  • 19
  • 1
    What you have is a URL that returns a response containing a JSON string. Are you asking how to request something from a URL? Because that would depend a lot on the language or tool that you're using. Be more specific. – jonvuri Sep 17 '12 at 13:37
  • 1
    This question is confusing. Don't you get the JSON object by using the URL you mentioned? What do you mean by getting the JSON object from a URL? please clarify. – Steven Sep 17 '12 at 13:37

12 Answers12

232

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.

Varun W.
  • 242
  • 2
  • 14
Dan Barzilay
  • 4,974
  • 5
  • 27
  • 39
190

If you want to do it in plain javascript, you can define a function like this:

var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status === 200) {
        callback(null, xhr.response);
      } else {
        callback(status, xhr.response);
      }
    };
    xhr.send();
};

And use it like this:

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(err, data) {
  if (err !== null) {
    alert('Something went wrong: ' + err);
  } else {
    alert('Your query count: ' + data.query.count);
  }
});

Note that data is an object, so you can access its attributes without having to parse it.

Robin Hartmann
  • 2,087
  • 1
  • 15
  • 26
  • why use `.onload = function() {` when you can use `.onreadystatechange = function() { if (xhr.readState === 4) {` I mean sure, it's shorter but you're sacrificing a great deal of support for saving a couple of characters. This is not code-golf – Downgoat Jul 13 '16 at 00:59
  • 4
    It's not only shorter, but it also seems to be a tad more reliable according to [this post](http://stackoverflow.com/a/19247992/3859863). And [caniuse.com](http://caniuse.com/#search=onload) says it's supported by everything except IE8, so as long as you don't need to support IE8, I don't see why you wouldn't use onload. – Robin Hartmann Jul 14 '16 at 10:43
  • @MikeySkullivan I wanted to know one thing, why is that i am getting responseText and responseXML as undefined though the response status = 200? – hrushi Nov 13 '16 at 18:06
  • 1
    @hrushi If they are undefined, you're accessing them in a wrong way or in the wrong context. Remember, you have to use xhr.responseText and xhr.responseXML and they are only available within the getJSON function definition block, not outside it. – Robin Hartmann Nov 15 '16 at 11:56
  • I'm trying to use this example but I get the error "ReferenceError: XMLHttpRequest is not defined" – Mitchell D Jun 10 '18 at 01:46
  • 2
    @MitchellD Are you using Node.js? Then take a look over [here](https://stackoverflow.com/a/32604544). But next time try googling for the error first, the link I posted is the first result that comes up when I type the error into Google. – Robin Hartmann Jun 11 '18 at 12:41
150

With Chrome, Firefox, Safari, Edge, and Webview you can natively use the fetch API which makes this a lot easier, and much more terse.

If you need support for IE or older browsers, you can also use the fetch polyfill.

let url = 'https://example.com';

fetch(url)
.then(res => res.json())
.then(out =>
  console.log('Checkout this JSON! ', out))
.catch(err => { throw err });

MDN: Fetch API

Even though Node.js does not have this method built-in, you can use node-fetch which allows for the exact same implementation.

DBrown
  • 5,111
  • 2
  • 23
  • 24
  • 8
    Ugh.. this doesn't even compile in IE11. Why is IE such junk? – dano Aug 09 '17 at 22:03
  • 5
    You can always use the github/fetch polyfill to overcome this issue. – DBrown Aug 10 '17 at 02:49
  • @dano it's the arrow functions. Use regular functions or Babel to transpile – Phil Oct 10 '19 at 05:46
  • 1
    @Phil thanks for pointing out ES6. The biggest issue with IE11 is that fetch is not a supported API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API It should also be known that the fetch polyfill needed for IE11 is purely ES5 (due to lack of support), so there is no actual need for ES6 transpilation unless you absolutely need it otherwise. If the only reason to add it is to support the fetch idiom (if the polyfill even supports it), using babel-polyfill is a better option. Best of luck! – DBrown Oct 12 '19 at 21:52
  • Firefox 104: `Uncaught SyntaxError: expected expression, got keyword 'throw'` – ar2015 Sep 06 '22 at 19:44
  • Firefox wants you to add braces to catch arrow function, or simply remove the catch. – DBrown Sep 09 '22 at 02:29
40

ES8(2017) try

obj = await (await fetch(url)).json();

async function load() {
    let url = 'https://my-json-server.typicode.com/typicode/demo/db';
    let obj = await (await fetch(url)).json();
    console.log(obj);
}

load();

you can handle errors by try-catch

async function load() {
    let url = 'http://query.yahooapis.com/v1/publ...';
    let obj = null;
    
    try {
        obj = await (await fetch(url)).json();
    } catch(e) {
        console.log('error');
    }
    
    console.log(obj);
}

load();
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
8

Define a function like:

fetchRestaurants(callback) {
    fetch(`http://www.restaurants.com`)
       .then(response => response.json())
       .then(json => callback(null, json.restaurants))
       .catch(error => callback(error, null))
}

Then use it like this:

fetchRestaurants((error, restaurants) => {
    if (error) 
        console.log(error)
    else 
        console.log(restaurants[0])

});
Dan Alboteanu
  • 9,404
  • 1
  • 52
  • 40
  • 1
    Given that there are many existing answers, please mention what about this answer makes it worth adding to the discussion. Usage of fetch has been mentioned in several existing answers. – ToolmakerSteve Oct 06 '19 at 10:40
  • 2
    This is the only relevant answer in 2020. It is simply a fetch which needs a callback for when an asynchronous event is completed. Easy and elegant – lesolorzanov Feb 10 '20 at 13:23
  • why isn't `fetch` awaited in this case? I am confused, I keep seeing examples where it is awaited and being called plainly – Pynchia Jun 14 '20 at 14:06
8

Axios is a promise based HTTP client for the browser and node.js.

It offers automatic transforms for JSON data and it's the official recommendation from the Vue.js team when migrating from the 1.0 version which included a REST client by default.

Performing a GET request

// Make a request for a user with a given ID
axios.get('http://query.yahooapis.com/v1/publ...')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Or even just axios(url) is enough as a GET request is the default.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
6

async function fetchDataAsync(url) {
    const response = await fetch(url);
    console.log(await response.json());
}

fetchDataAsync('paste URL');
Tom Price
  • 138
  • 8
zq-jhon
  • 109
  • 1
  • 7
  • 1
    Please describe something about your answer. – Angel F Syrus Aug 23 '19 at 06:32
  • 2
    Given that there are many existing answers, please mention what about this answer makes it worth adding to the discussion. Usage of `fetch` has been mentioned in several existing answers. Usage of `await/async` with fetch, was described in [Kamil's answer](https://stackoverflow.com/a/55784549/199364). – ToolmakerSteve Oct 06 '19 at 10:42
  • Best answer. Concise and worked for me. – ar2015 Sep 06 '22 at 19:51
0
//Resolved
const fetchPromise1 = fetch(url);
    fetchPromise1.then(response => {
      console.log(response);
    });


//Pending
const fetchPromise = fetch(url);
console.log(fetchPromise);
ashish bandiwar
  • 378
  • 1
  • 3
  • 12
  • 2
    this is code only answer! add some explanation to the post – Ram Ghadiyaram Aug 23 '19 at 16:09
  • 2
    Given that there are many existing answers, please mention what about this answer makes it worth adding to the discussion. Usage of `fetch` has been mentioned in several existing answers. – ToolmakerSteve Oct 06 '19 at 10:41
0

this morning, i also had the same doubt and now its cleared i had just used JSON with 'open-weather-map'(https://openweathermap.org/) api and got data from the URL in the index.html file, the code looks like this:-

 //got location
 var x = document.getElementById("demo");
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(weatherdata);
      } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
      }
    //fetch openweather map url with api key
    function weatherdata(position) {
//put corrdinates to get weather data of that location
      fetch('https://api.openweathermap.org/data/2.5/weather?lat='+position.coords.latitude+'&lon='+position.coords.longitude+'&appid=b2c336bb5abf01acc0bbb8947211fbc6')
      .then(response => response.json())
      .then(data => {
      console.log(data);
      document.getElementById("demo").innerHTML = 
      '<br>wind speed:-'+data.wind.speed + 
      '<br>humidity :-'+data.main.humidity + 
      '<br>temprature :-'+data.main.temp  
      });
    }
  <div id="demo"></div>

i had give api key openly because i had free subscription, just have a free subscriptions in beginning. you can find some good free api's and keys at "rapidapi.com"

user12449933
  • 170
  • 1
  • 6
0

as @DanAlboteanu answer in this page and some error corection of that javascript my suggested code is:

fetchRestaurants((error, data) => {
    if (error)
        console.log(error); 
    else
        console.log(data)

});

and fetchRestaurants method is(please replace your json url with {your url of json data}):

function fetchRestaurants(callback) {
    fetch("{your url of json data}")
       .then(response => response.json())
       .then(json => callback(null, json))
       .catch(error => callback(error, null))
}
Ali Rasouli
  • 1,705
  • 18
  • 25
0
            async function Fetching()
            {
                const response = await fetch('https://business-api-account.github.io/API.json');
                const jsonData = await response.json();
                console.log(jsonData);
            }

            Fetching();

When fetching a file it is required to use an awaited asynchronous method call. The file content must be extracted asynchronously and awaited because the fetch() method is returning the response in with a promise, meaning that the response is promised, not guaranteed. By awaiting the call, the program will wait in the point where the method call is performed until the promise is returned, and not continue the execution if the promise was not received yet, with the file content or not.

teodor mihail
  • 343
  • 3
  • 7
-1

You can access JSON data by using fetch() in JavaScript

Update url parameter of fetch() with your url.

fetch(url)
    .then(function(response){
        return response.json();
    })
    .then(function(data){
        console.log(data);
    })

Hope It helps, it worked perfectly for me.

  • 3
    This appears to be a duplicate of [DBrown's answer](https://stackoverflow.com/a/43175774/199364). Please don't add duplicate answers. If there is something unique about this answer, then mention DBrown's answer, and explain what is different about yours. – ToolmakerSteve Oct 06 '19 at 10:35