如何在JavaScript中从URL获取JSON?

问题描述 投票:130回答:7

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

javascript json
7个回答
140
投票

你可以使用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解决方案的答案:https://stackoverflow.com/a/2499647/1361042


104
投票

如果你想在普通的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是一个对象,因此您可以访问其属性而无需解析它。


57
投票

借助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,它允许完全相同的实现。


4
投票

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

它提供了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请求是默认的。


1
投票

功能:

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

});

1
投票

尝试

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

async function get() {
    let url = 'https://my-json-server.typicode.com/typicode/demo/db'
    let obj = await (await fetch(url)).json();
    console.log(obj);
}
<button onclick="get()">Load data</button>

0
投票

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

使用您的网址更新fetch()的url参数。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.