javascript - 如何在 JavaSCript 中将 JSON 数据存储在变量中?

标签 javascript json async-await es6-promise

我需要函数 ** 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>}
  • 如果数据存储在变量中(例如 ** obj **),也会很有用。我尝试了下一个代码,但它也不起作用。
  • 代码:

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

    输出:

    undefinded
    

    最佳答案

    异步函数始终返回Promise。使用如下所示的 .then() block 来获取数据:)

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

    下面的这个函数是异步并且它将返回一个promise。当您尝试 console.log(getJson()) 时,您的情况会返回已解决的 promise 。为了从已解决的 Promise 中获取值,我们需要 .then() block ,并且回调具有数据。

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

    关于javascript - 如何在 JavaSCript 中将 JSON 数据存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65434502/

    相关文章:

    javascript - AngularJS 中的滚动事件

    javascript - 使用 Tempo 转换树结构

    jquery - 解析嵌套的 json 对象

    c# - 异步方法恢复后值未更新

    javascript - Post 请求不起作用,错误显示 "cannot post/addstudent/add"

    javascript - 在不知道前一个节点的情况下访问 Firebase 节点

    java - JSON 解析问题未解决

    async-await - 如何等待订阅功能以角度 8 完成?

    c# - 如何在返回任务的方法中调用异步方法?

    javascript - 如果在选择列表中选择了一个选项,如何在另一个选择列表中禁用具有相同值的选项