Cómo obtener JSON desde URL en Javascript?


Esta URL devuelve JSON:

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

Probé esto, y no funcionó:

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

console.log(count) // should be 1

¿Cómo puedo obtener un objeto JavaScript de la respuesta JSON de esta URL?

Author: haykam, 2012-09-17

5 answers

Puede usar jQuery .getJSON() función:

$.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) {
    //data is the JSON string
});

Si no desea usar jQuery, debe mirar esta respuesta para una solución JS pura: https://stackoverflow.com/a/2499647/1361042

 117
Author: Dan Barzilay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:22

Si desea hacerlo en javascript plano, puede definir una función como esta:

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();
};

Y úsalo así:

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);
  }
});

Tenga en cuenta que data es un objeto, por lo que puede acceder a sus atributos sin tener que analizarlo.

 89
Author: Robin Hartmann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-24 16:35:23

Con Chrome, Firefox, Safari, Edge y Webview puede usar de forma nativa la API fetch, lo que hace que esto sea mucho más fácil y mucho más conciso.

Si necesita soporte para navegadores IE o antiguos, también puede usar 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

Aunque Nodo.js no tiene este método incorporado, puede usar node-fetch que permite exactamente la misma implementación.

 38
Author: DBrown,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-02 16:23:41

Axios es un cliente HTTP basado en promesas para el navegador y el nodo.js .

Ofrece transformaciones automáticas para datos JSON y es la recomendación oficial del Vue.js team al migrar desde la versión 1.0 que incluía un cliente REST por defecto.

Realizando una solicitud GET

// 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);
  });

O incluso simplemente axios(url) es suficiente como una solicitud GET es el valor predeterminado.

 2
Author: Emile Bergeron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-06 23:08:58

Función:

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

Uso:

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

});
 1
Author: Dan Alboteanu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-19 20:17:01