这个URL返回JSON:

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

我试过了,但没有用:

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

console.log(count) // should be 1

如何从这个URL的JSON响应中获得JavaScript对象?


你可以使用jQuery .getJSON()函数:

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

如果你不想使用jQuery,你应该看看这个纯JS解决方案的答案。


如果你想在纯javascript中实现,你可以这样定义一个函数:

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

像这样使用它:

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

注意,data是一个对象,因此您可以访问它的属性,而不必解析它。


对于Chrome, Firefox, Safari, Edge和Webview,您可以本机使用fetch API,这使得这更容易,更简洁。

如果你需要对IE或更老的浏览器的支持,你也可以使用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:获取API

即使Node.js没有内置这个方法,你也可以使用node-fetch来实现完全相同的实现。


定义如下函数:

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

然后这样使用它:

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

});

Axios是面向浏览器和node.js的基于承诺的HTTP客户端。

它提供了JSON数据的自动转换,这是Vue.js团队在从默认包含REST客户端的1.0版本迁移时的官方推荐。

执行GET请求 //对给定ID的用户进行请求 axios.get(“http://query.yahooapis.com/v1/publ..”。) .then(函数(响应){ console.log(响应); }) .catch(函数(错误){ console.log(错误); });

或者甚至只要axios(url)就足够了,因为GET请求是默认的。


ES8(2017) 尝试

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

异步函数加载(){ 让url = 'https://my-json-server.typicode.com/typicode/demo/db'; 让obj = await (await fetch(url)).json(); console.log (obj); } load ();

可以通过try-catch处理错误

异步函数加载(){ 让url = 'http://query.yahooapis.com/v1/publ…'; 让obj = null; 尝试{ Obj = await (await fetch(url)).json(); } catch(e) { console.log('错误'); } console.log (obj); } load ();


你可以在JavaScript中使用fetch()访问JSON数据

用你的url更新fetch()的url参数。

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

希望有帮助,对我来说很有效。


fetchDataAsync(url) { Const response = await fetch(url); console.log(等待response.json ()); } fetchDataAsync(“粘贴URL”);


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


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

今天早上,我也有同样的怀疑,现在它消除了 我刚刚使用JSON和'open-weather-map'(https://openweathermap.org/) api,并从index.html文件中的URL中获得数据, 代码看起来像这样:-

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

我公开给API密钥,因为我有免费订阅,只是一开始有一个免费订阅。 你可以在“rapidapi.com”上找到一些不错的免费api和密钥。


作为@DanAlboteanu在本页的答案和javascript的一些错误纠正,我建议的代码是:

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

});

and fetchRestaurants方法是(请将您的json url替换为{您的json数据url}):

function fetchRestaurants(callback) {
    fetch("{your url of json data}")
       .then(response => response.json())
       .then(json => callback(null, json))
       .catch(error => callback(error, null))
}