[javascript] 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?

This question is related to javascript json

The answer is


ES8(2017) try

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

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

you can handle errors by try-catch

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


//Resolved
const fetchPromise1 = fetch(url);
    fetchPromise1.then(response => {
      console.log(response);
    });


//Pending
const fetchPromise = fetch(url);
console.log(fetchPromise);

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.


_x000D_
_x000D_
async function fetchDataAsync() {_x000D_
    const response = await fetch('paste URL');_x000D_
    console.log(await response.json())_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
fetchDataAsync();
_x000D_
_x000D_
_x000D_


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.


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])

});

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.


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:-

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

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"


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.