这个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解决方案的答案。

其他回答

对于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来实现完全相同的实现。

你可以使用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解决方案的答案。

定义如下函数:

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

});

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

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

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

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

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