【问题标题】:How to store JSON data in a variable in JavaSCript?如何将 JSON 数据存储在 JavaSCript 中的变量中?
【发布时间】:2021-04-02 16:19:28
【问题描述】:

我需要函数**getJson()**从json中获取和返回数据。

JSON(文件.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. 我尝试使用异步功能但不成功。

代码:

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

输出:

Promise {<pending>}
  1. 如果数据存储在一个变量中,例如在 ** obj ** 中,它也会很有用。我尝试了下一个代码,但也没有用。

代码:

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

输出:

undefinded

【问题讨论】:

  • 在第一个示例中尝试console.log(await getJson()),在第二个示例中尝试await getJson(); console.log(obj)
  • 检查我的答案。这是主要原因。试试看,如果这个答案对你有帮助,请接受答案并投票:)

标签: javascript json async-await es6-promise


【解决方案1】:

Async function 始终返回 Promise。使用.then() 块如下所示获取数据:)

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

下面的这个函数是async,它会返回一个promise。当您尝试 console.log(getJson()) 时,您的情况会返回已解决的承诺。要从已解决的承诺中取回值,我们需要 .then() 块并且回调包含数据。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 2013-04-26
    相关资源
    最近更新 更多