0

I try to import a json file (data.json) in javascript file. This is my code:

function grabData() {
    fetch("./data.json")
    .then(response => {
        return response.json().then(function(data) {
            var dataExport = data;
            console.log(dataExport)
        });
    })

}

grabData()
console.log(dataExport)

However, the variable (dataExport) works only on a function.

How i can access at this variable outside of my function?

BerretMan
  • 95
  • 6
  • 2
    Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Sven Eberth Jun 05 '21 at 20:14

2 Answers2

2

To access the data outside the function, you have to return it:

function grabData() {
  return fetch("./data.json")
    .then(response => response.json());
}
//or
async function grabData() {
  const response = await fetch("./data.json");
  return await response.json();
}

grabData().then(data => console.log(data));

//or
let data = await grabData();
console.log(data);

jalepi
  • 184
  • 3
  • Thanks you, the second option work, you saved my project. However, when I try to stock this request in variable, this return a "Promise". How i can only saved the value of my json, the "PromiseResult" – BerretMan Jun 05 '21 at 21:06
  • If you want to have the result of a Promise, you can either await for it `let captureData = await grabData();` or capture it inside the callback `grabData().then(data => { captureData = data; })` – jalepi Jun 06 '21 at 05:49
1

Vanilla JavaScript does not parse the JSON into an object natively. You need to parse the JSON into an object using the JSON Parse method.

  • Also I would advise from using "var" and trying to hoist the variable outside of a function. "dataexport" should be an internal variable inside of the function. If you want the function to assign the value to a variable pass it in as a parameter.

https://www.w3schools.com/js/js_json_parse.asp

Once it is parsed you can read from it as an object.

let dataExport;

function grabData(returnData) {
    fetch("./data.json")
    .then(response => {
        return response.json().then(function(data) {
            returnData = JSON.parse(data);
            console.log(returnData);
        });
    })

}

grabData(dataExport);
cobb208
  • 55
  • 1
  • 7