【问题标题】:How to use async json data?如何使用异步 json 数据?
【发布时间】:2020-03-05 22:17:57
【问题描述】:

我正在使用 node.js。 我已经设法使用异步加载和解析我的 .json 文件。 整个概念对我来说非常新,我可以在控制台中看到我的 .json 数据,但我不确定现在如何实际使用我的数据,..

   async function getJsonFile() {
       let response = await fetch('example.json');
       let responsejson = await response.json();
       let str = JSON.stringify(responsejson);
       let jsonData = JSON.parse(str);

       return jsonData;
    };

    getJsonFile().then(console.log);  // I see my .json file in console, how can I use it ?
}

【问题讨论】:

    标签: node.js json parsing asynchronous


    【解决方案1】:

    要实际使用 JSON 中的内容,您需要将其存储为变量,然后以对您有用的方式访问它。您可以使用property accessors 访问对象的属性。

    // Save as variable
    var json = await getJsonData();
    // Do something with properties of data
    console.log(json['key']);
    

    【讨论】:

      【解决方案2】:

      如果您尝试使用 json 中的数据,您可以这样做:

      // Use this in an async function
      const data = await getJsonFile();
      // Then get value of one key
      console.log(data.key); // from {key: "value"}, you'll get value
      

      【讨论】:

        【解决方案3】:

        我认为这是这样做的方法:

        var json = await getJsonData();
        // use it
        

        【讨论】:

        • 我的问题是如何实际使用它,因为现在我只知道如何使用“console.log”在控制台中显示,但我似乎无能为力,到目前为止我尝试过的一切失败; /
        猜你喜欢
        • 1970-01-01
        • 2015-07-02
        • 2019-03-26
        • 1970-01-01
        • 1970-01-01
        • 2018-08-25
        • 2016-08-20
        • 2018-07-21
        • 1970-01-01
        相关资源
        最近更新 更多