如何在JavaSCript中的变量中存储JSON数据?
How to store JSON data in a variable in JavaSCript?
我需要函数 ** getJson () ** 来获取和 return 来自 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"
}
]
- 我尝试使用异步函数但没有成功。
代码:
async function getJson() {
const response = await fetch('file.json');
const data = await response.json();
return data;
}
console.log(getJson());
输出:
Promise {<pending>}
- 如果数据存储在变量中,例如在 ** obj ** 中,这也会很有用。我尝试了下一个代码,但它也没有用。
代码:
var obj;
async function getJson() {
const response = await fetch('file.json');
obj = await response.json();
}
console.log(obj);
输出:
undefinded
一个 Async function
总是 return 一个 Promise
。使用如下所示的 .then()
块来取回数据:)
getJson().then(data=>console.log(data);
下面这个函数是 async
并且它将 return 一个承诺。当您尝试 console.log(getJson())
一个已解决的承诺时,您的情况是 returned。要从已解决的承诺中取回价值,我们需要 .then()
块并且回调具有数据。
async function getJson() {
const response = await fetch('file.json');
const data = await response.json();
return data;
}
getJson().then(data=>console.log(data));
我需要函数 ** getJson () ** 来获取和 return 来自 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"
}
]
- 我尝试使用异步函数但没有成功。
代码:
async function getJson() {
const response = await fetch('file.json');
const data = await response.json();
return data;
}
console.log(getJson());
输出:
Promise {<pending>}
- 如果数据存储在变量中,例如在 ** obj ** 中,这也会很有用。我尝试了下一个代码,但它也没有用。
代码:
var obj;
async function getJson() {
const response = await fetch('file.json');
obj = await response.json();
}
console.log(obj);
输出:
undefinded
一个 Async function
总是 return 一个 Promise
。使用如下所示的 .then()
块来取回数据:)
getJson().then(data=>console.log(data);
下面这个函数是 async
并且它将 return 一个承诺。当您尝试 console.log(getJson())
一个已解决的承诺时,您的情况是 returned。要从已解决的承诺中取回价值,我们需要 .then()
块并且回调具有数据。
async function getJson() {
const response = await fetch('file.json');
const data = await response.json();
return data;
}
getJson().then(data=>console.log(data));