如何在Javascript中从URL获取JSON?

Yiğ*_*lik 146 javascript json

此URL返回JSON:

{
  query: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

我试过这个,但它不起作用:

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

console.log(count) // should be 1
Run Code Online (Sandbox Code Playgroud)

如何从此URL的JSON响应中获取JavaScript对象?

Dan*_*lay 149

你可以使用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
});
Run Code Online (Sandbox Code Playgroud)

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

  • 如果声明'JSON在'data`变量中'可能会更清楚 (13认同)
  • 您指向的纯JavaScript示例是针对JSONP的,不适用于该问题。 (2认同)

Rob*_*ann 112

如果你想在普通的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();
};
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

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);
  }
});
Run Code Online (Sandbox Code Playgroud)

请注意,这data是一个对象,因此您无需解析它就可以访问其属性.

  • 它不仅更短,而且根据[这篇文章](http://stackoverflow.com/a/19247992/3859863),它似乎也更可靠.并且[caniuse.com](http://caniuse.com/#search=onload)表示除了IE8之外的所有内容都支持它,所以只要你不需要支持IE8,我就不明白为什么你不会'使用onload. (3认同)
  • @MitchellD 你在使用 Node.js 吗?然后看看[这里](/sf/answers/2282318111/)。但是下次尝试先用谷歌搜索错误时,我发布的链接是我在谷歌中输入错误时出现的第一个结果。 (2认同)

DBr*_*own 65

借助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 });
Run Code Online (Sandbox Code Playgroud)

MDN:获取API

即使Node.js没有内置此方法,您也可以使用node-fetch,它允许完全相同的实现.

  • 呃..这甚至都没有在IE11中编译.IE为何如此垃圾? (5认同)
  • 您始终可以使用github/fetch polyfill来解决此问题. (4认同)

Kam*_*ski 23

ES8(2017) 尝试

obj = await (await fetch(url)).json();
Run Code Online (Sandbox Code Playgroud)

obj = await (await fetch(url)).json();
Run Code Online (Sandbox Code Playgroud)

你可以通过 try-catch 处理错误

async function load() {
    let url = 'https://my-json-server.typicode.com/typicode/demo/db';
    let obj = await (await fetch(url)).json();
    console.log(obj);
}

load();
Run Code Online (Sandbox Code Playgroud)

  • 这看起来真的很好。与其他方法相比如何? (2认同)

Dan*_*anu 7

定义一个函数,如:

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

然后像这样使用它:

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

});
Run Code Online (Sandbox Code Playgroud)

  • 这是 2020 年唯一相关的答案。它只是一个 fetch,需要在异步事件完成时进行回调。轻松优雅 (2认同)

Emi*_*ron 7

Axios用于浏览器和node.js的基于Promise 的HTTP客户端

它提供了JSON数据的自动转换功能,这是Vue.js团队的正式建议,当从默认版本(包括REST客户端)的1.0版本进行迁移时。

执行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);
  });
Run Code Online (Sandbox Code Playgroud)

甚至仅仅axios(url)是一个GET请求就足够了,因为请求是默认的。


小智 6

async function fetchDataAsync(url) {
    const response = await fetch(url);
    console.log(await response.json());
}

fetchDataAsync('paste URL');
Run Code Online (Sandbox Code Playgroud)

  • 鉴于已有许多答案,请说明该答案的哪些内容值得添加到讨论中。在几个现有的答案中已经提到了“fetch”的用法。[Kamil 的回答](/sf/answers/3904918461/) 中描述了“await/async”与 fetch 的用法。 (2认同)