Saving fetched JSON into variable

泪湿孤枕 提交于 2020-07-20 07:59:11

问题


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?

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

回答1:


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

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




回答2:


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.

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

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.




回答3:


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/




回答4:


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


来源:https://stackoverflow.com/questions/48474970/saving-fetched-json-into-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!