Vanilla Javascript,如何读取本地 JSON 文件

Vanilla Javascript, how to read local JSON file

我是 javascript 的新手,我正在尝试使用 javascript 读取 JSON 文件,但我不知道如何从承诺结果中访问数据。我的数据在 .json 文件调用 Data.json 中,我在内部使用 fetch 来承诺加载 JSON 文件和 return 结果。如何从承诺结果中获取数据?

JSON 文件中的数据

{
 "data": {
   "reviewer": [
  {
    "id": 1,
    "name": "susan smith",
    "job": "web developer",
    "text": "I'm baby meggings twee health goth +1. Bicycle rights tumeric chartreuse before they sold out chambray pop-up. Shaman humblebrag pickled coloring book salvia hoodie, cold-pressed four dollar toast everyday carry"
  },
  {
    "id": 2,
    "name": "anna johnson",
    "job": "web designer",
    "text": "Helvetica artisan kinfolk thundercats lumbersexual blue bottle. Disrupt glossier gastropub deep v vice franzen hell of brooklyn twee enamel pin fashion axe.photo booth jean shorts artisan narwhal."
  },
  {
    "id": 3,
    "name": "peter jones",
    "job": "intern",
    "text": "Sriracha literally flexitarian irony, vape marfa unicorn. Glossier tattooed 8-bit, fixie waistcoat offal activated charcoal slow-carb marfa hell of pabst raclette post-ironic jianbing swag."
  },
  {
    "id": 4,
    "name": "bill anderson",
    "job": "the boss",
    "text": "Edison bulb put a bird on it humblebrag, marfa pok pok heirloom fashion axe cray stumptown venmo actually seitan. VHS farm-to-table schlitz, edison bulb pop-up 3 wolf moon tote bag street art shabby chic. "
  }
]
}}

JavaScript代码

const data = new Promise((resolve, reject) => {
fetch('./Data.json')
    .then(respond => {
        resolve(respond.json())
    }).catch(err => {
        reject(err)
 })
})

console.log(data)

当我 运行 代码时,我在控制台中得到了这个。

fetch() returns一个Promise,所以你不需要自己创建一个。 fetch 返回的 Promise 使用 Response object on which you need to call .json() 方法来获取实际数据。此方法也是 returns 一个 Promise,因此您需要链接另一个 then() 方法调用。

fetch('./Data.json')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

详情见: