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?

1

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.