Search code examples
javascriptjsonfetch-api

Saving fetched JSON into variable


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

Solution

  • 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.