如何从 JavaScript 中的 URL 获取 JSON?

Posted

技术标签:

【中文标题】如何从 JavaScript 中的 URL 获取 JSON?【英文标题】:How to get JSON from URL in JavaScript? 【发布时间】:2012-09-09 17:38:56 【问题描述】:

This 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 对象?

【问题讨论】:

您拥有的是一个返回包含 JSON 字符串的响应的 URL。您是在问如何从 URL 请求某些东西吗?因为这在很大程度上取决于您使用的语言或工具。更具体。 这个问题令人困惑。您不是通过使用您提到的 URL 来获取 JSON 对象吗?从 URL 获取 JSON 对象是什么意思?请澄清。 【参考方案1】:

你可以使用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,您应该查看 this answer 以获得纯 JS 解决方案。

【讨论】:

次要问题,但如果它声明“JSON 在 data 变量中”可能会更清楚 您指向的纯 JavaScript 示例是针对 JSONP 的,它不适用于该问题。 这对我来说是第一次尝试。这永远不会发生!【参考方案2】:

借助 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: Fetch API

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

【讨论】:

呃.. 这甚至不能在 IE11 中编译。为什么 IE 这么垃圾? 你总是可以使用 github/fetch polyfill 来解决这个问题。 @dano 这是箭头函数。使用常规函数或 Babel 进行转译 @Phil 感谢您指出 ES6。 IE11 最大的问题是 fetch 不是一个受支持的 API:developer.mozilla.org/en-US/docs/Web/API/Fetch_API 还应该知道 IE11 所需的 fetch polyfill 是纯 ES5(由于缺乏支持),因此实际上不需要 ES6 转译,除非否则你绝对需要它。如果添加它的唯一原因是支持 fetch 习惯用法(如果 polyfill 甚至支持它),则使用 babel-polyfill 是更好的选择。祝你好运!【参考方案3】:

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


fetchDataAsync('paste URL');

【讨论】:

请描述一下您的回答。 鉴于已有许多答案,请提及该答案的哪些方面值得加入讨论。几个现有答案中提到了fetch 的用法。 await/async 与 fetch 的用法在 Kamil's answer 中进行了描述。【参考方案4】:

作为 @DanAlboteanu 在此页面中的回答以及该 javascript 的一些错误修正,我建议的代码是:

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

);

而 fetchRestaurants 方法是(请将您的 json url 替换为 your url of json data):

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

【讨论】:

【参考方案5】:

今天早上,我也有同样的疑问,现在解决了 我刚刚将 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  
      );
    
  &lt;div id="demo"&gt;&lt;/div&gt;

我公开提供了 api 密钥,因为我有免费订阅,刚开始时有免费订阅。 您可以在“rapidapi.com”找到一些不错的免费 API 和密钥

【讨论】:

【参考方案6】:

定义如下函数:

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

);

【讨论】:

鉴于已有许多答案,请提及此答案的哪些内容值得加入讨论。几个现有答案中都提到了 fetch 的用法。 这是 2020 年唯一相关的答案。它只是一个 fetch,需要在异步事件完成时进行回调。轻松优雅 为什么在这种情况下不等待fetch?我很困惑,我不断看到等待并被简单调用的示例【参考方案7】:

ES8(2017) 尝试

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

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

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

async function load() 
    let url = 'http://query.yahooapis.com/v1/publ...';
    let obj = null;
    
    try 
        obj = await (await fetch(url)).json();
     catch(e) 
        console.log('error');
    
    
    console.log(obj);


load();

【讨论】:

这看起来真不错。这与其他方法相比如何?【参考方案8】:
//Resolved
const fetchPromise1 = fetch(url);
    fetchPromise1.then(response => 
      console.log(response);
    );


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

【讨论】:

这是代码唯一的答案!在帖子中添加一些解释 鉴于已有许多答案,请提及此答案的哪些内容值得加入讨论。几个现有答案中提到了fetch 的用法。【参考方案9】:

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

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

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

希望它有所帮助,它对我来说非常有用。

【讨论】:

这似乎与 DBrown's answer 重复。请不要添加重复的答案。如果此答案有什么独特之处,请提及 DBrown 的答案,并说明您的答案有何不同。【参考方案10】:

Axios 是一个基于promise 的浏览器和node.js 的HTTP 客户端

它为 JSON 数据提供自动转换,从默认包含 REST 客户端的 1.0 版本迁移时为 the official recommendation from the Vue.js team。

执行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);
  );

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

【讨论】:

【参考方案11】:

如果你想用纯 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 是一个对象,因此您无需解析即可访问其属性。

【讨论】:

当你可以使用.onreadystatechange = function() if (xhr.readState === 4) 时为什么要使用.onload = function() 我的意思是,它更短,但是你牺牲了很多支持来保存几个字符。这不是代码高尔夫 根据this post,它不仅更短,而且似乎更可靠。而caniuse.com 说除了IE8之外的所有东西都支持,所以只要你不需要支持IE8,我不明白你为什么不使用onload。 @MikeySkullivan 我想知道一件事,为什么我得到 responseText 和 responseXML 为 undefined 虽然响应状态 = 200? @hrushi 如果它们未定义,则您以错误的方式或在错误的上下文中访问它们。请记住,您必须使用 xhr.responseText 和 xhr.responseXML,它们仅在 getJSON 函数定义块内可用,而不是在它之外。 @MitchellD 你在使用 Node.js 吗?然后看看here。但是下次尝试先在谷歌上搜索错误时,我发布的链接是我在 Google 中输入错误时出现的第一个结果。

以上是关于如何从 JavaScript 中的 URL 获取 JSON?的主要内容,如果未能解决你的问题,请参考以下文章

如何从 JavaScript 中的 URL 获取 JSON?

如何从javascript中的url获取参数值? [复制]

如何从javascript中的url获取id? [复制]

如何从 javascript 中的 URL 获取 File() 或 Blob()?

如何检查获取的响应是不是是javascript中的json对象

从 Javascript 中的 url 获取 JSON 文件,React Native