这个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对象?
如果你想在纯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是一个对象,因此您可以访问它的属性,而不必解析它。
作为@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))
}
如果你想在纯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是一个对象,因此您可以访问它的属性,而不必解析它。