阅读 JSON 客户端 vanilla javascript 中的网站源代码

Read JSON that is in website source in client-side vanilla javascript

我有一个简单的 JSON 文件,位于我网站源代码中的 data 文件夹中。在 javascript 脚本中,我想读取 JSON 并使用其中的信息更新 DOM。我网站的文件结构是这样的

css
design
html
  |____ category.html (this is where the script will be loaded)
js
  |____updateDomScript.js (this is the script that should be loaded)
src
  |____data
          |____jsonFile.json (this is the json that needs to be loaded)

我显然不能使用 nodejs 中的 require(),因为这是在客户端。我不知道 FileReader 在这里如何工作。我需要做的就是从 ../src/data/jsonFile.json.

中读取这个 JSON 文件

我说的是第三个答案,可以用fetch语句。如果您对 fetch 感到困惑,那么我建议您先在线查找。

fetch("path/to/file")
  .then(response => response.json())
  .then(json => console.log(json));