如何从JavaScript中的URL获取JSON?

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

如果你不想使用jQuery,你应该看看这个纯JS解决scheme的答案: https : //stackoverflow.com/a/2499647/1361042

如果你想用普通的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是一个对象,所以您可以访问它的属性而不必parsing它。

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

如果您需要IE或更旧浏览器的支持,您也可以使用获取填充 。

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