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


当前回答

作为@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中使用fetch()访问JSON数据

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

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

希望有帮助,对我来说很有效。

ES8(2017) 尝试

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

异步函数加载(){ 让url = 'https://my-json-server.typicode.com/typicode/demo/db'; 让obj = await (await fetch(url)).json(); console.log (obj); } load ();

可以通过try-catch处理错误

异步函数加载(){ 让url = 'http://query.yahooapis.com/v1/publ…'; 让obj = null; 尝试{ Obj = await (await fetch(url)).json(); } catch(e) { console.log('错误'); } console.log (obj); } load ();

作为@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))
}

Axios是面向浏览器和node.js的基于承诺的HTTP客户端。

它提供了JSON数据的自动转换,这是Vue.js团队在从默认包含REST客户端的1.0版本迁移时的官方推荐。

执行GET请求 //对给定ID的用户进行请求 axios.get(“http://query.yahooapis.com/v1/publ..”。) .then(函数(响应){ console.log(响应); }) .catch(函数(错误){ console.log(错误); });

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

//Resolved
const fetchPromise1 = fetch(url);
    fetchPromise1.then(response => {
      console.log(response);
    });


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