简体   繁体   中英

How to store JSON data in a variable in JavaSCript?

I need the function ** getJson () ** to fetch and return the data from json.

JSON (file.json):

    [
        {
                "01/01/2021":"Confraternização Universal",
                "15/02/2021":"Carnaval",
                "16/02/2021":"Carnaval",
                "02/04/2021":"Paixão de Cristo",
                "21/04/2021":"Tiradentes",
                "01/05/2021":"Dia do Trabalho",
                "03/06/2021":"Corpus Christi",
                "07/09/2021":"Independência do Brasil",
                "12/10/2021":"Nossa Sr.a Aparecida - Padroeira do Brasil",
                "02/11/2021":"Finados",
                "15/11/2021":"Proclamação da República",
                "25/12/2021":"Natal"
        }
]
  1. I tried to use the async function but was unsuccessful.

Code:

async function getJson() {
    const response = await fetch('file.json');
    const data = await response.json();
    return data;
}
console.log(getJson());

Output:

Promise {<pending>}
  1. It would also be useful if the data were stored in a variable, in ** obj ** for example. I tried the next code but it didn't work either.

Code:

var obj;
async function getJson() {
    const response = await fetch('file.json');
    obj = await response.json();
}
console.log(obj);

Output:

undefinded

An Async function always returns a Promise . Use .then() block as shown below to get the data back:)

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

This function below is async and it will return a promise. When you were trying to console.log(getJson()) a resolved promise is returned in your case. To get the value back from resolved promise we require .then() block and the callback has the data.

async function getJson() {
    const response = await fetch('file.json');
    const data = await response.json();
    return data;
}
getJson().then(data=>console.log(data));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM