javascript 将获取的 JSON 保存到变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48474970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:03:49  来源:igfitidea点击:

Saving fetched JSON into variable

javascriptjsonfetch

提问by J Hightow

I'm trying to get JSON saved into a variable, but it seems I don't understand everything here. I get JSON show up in console a once the way I like, but after I try to call it again later it only returns promise. How can I get JSON saved into a variable, so I could use objects in JSON later?

我试图将 JSON 保存到一个变量中,但似乎我不明白这里的所有内容。我以我喜欢的方式将 JSON 显示在控制台 a 中,但是在我稍后再次尝试调用它之后,它只返回 promise。如何将 JSON 保存到变量中,以便以后可以在 JSON 中使用对象?

var jsondata = fetch(url).then(
    function(u){ return u.json();}
  ).then(
    function(json){
      console.log(json);
    }
  )
console.log(jsondata);

采纳答案by Drago? Paul Marinescu

let jsondata;    
fetch(url).then(
        function(u){ return u.json();}
      ).then(
        function(json){
          jsondata = json;
        }
      )

Basically you need to assign your jsondatavariable once the promise resolves with the actual data. Currently, you're assigning the entire promise to your jsondatavariable which is not what you want.

基本上,jsondata一旦承诺解决了实际数据,您就需要分配变量。目前,您将整个承诺分配给您的jsondata变量,这不是您想要的。

回答by marcobiedermann

The fetch API is Promise based and will always return a new Promise either resolved or rejected. You have multiple options to store the result.

fetch API 是基于 Promise 的,并且将始终返回一个新的 Promise 已解决或拒绝。您有多种选择来存储结果。

Variable assignment

变量赋值

const data = [];

fetch(url)
    .then(response => response.json())
    .then(result => data.push(...result));

Unfortunately this might so somehow hacky because you do not know when the data variable is populated.

不幸的是,这在某种程度上可能有点麻烦,因为您不知道数据变量何时被填充。

Promise

承诺

function getData(url) {
    return fetch(url)
        .then(response => response.json())
        .then(result => result);
}

getData(URL)
    .then(result => console.log(result));

Anync & Await

Anync & Await

async function getData(url) {
    const response = await fetch(url);

    return response.json()
}

async function main() {
    const data = await getData(URL);

    console.log(data)
}

If you would ask me, I would go with async & await.

如果你问我,我会选择 async & await。

回答by Travis

Another option is using a callback as a parameter this way you aren't exposing a variable to global scope.

另一种选择是使用回调作为参数,这样您就不会将变量暴露给全局范围。

function getFromAPI(url, callback){
  var obj;
  fetch(url)
    .then(res => res.json())
    .then(data => obj = data)
    .then(() => callback(obj))
 }

getFromAPI('https://jsonplaceholder.typicode.com/posts', getData);

function getData(arrOfObjs){
  var results = "";
  arrOfObjs.forEach( (x) => {
    results += "<p> Id: " + x.id + "<ul>"
    Object.keys(x).forEach( (p) => {
        results += "<li>" + (p + ": " + x[p]) + "</li>";
    });
    results += "</ul> </p> <hr>"
  })
  results += "";
  document.getElementById("myDiv").innerHTML = results;
}

http://jsfiddle.net/5gch2yzw/

http://jsfiddle.net/5gch2yzw/

回答by A.Aleem11

You can create a separate function outside the fetch function to deal with json data like in below code the fetch function is passing the complete json object to another function called "data_function" we can proceed and work with JSON object in through this "data_function".

您可以在 fetch 函数之外创建一个单独的函数来处理 json 数据,如下面的代码所示,fetch 函数将完整的 json 对象传递给另一个名为“data_function”的函数,我们可以通过这个“data_function”继续处理 JSON 对象。

//fetch function
fetch(url).then(
function(u){ return u.json();}
).then(
function(json){
data_function(json); //calling and passing json to another function data_function
}
)

//another functions
function data_function(data){
alert(data.length); 
}