Skip to content
Advertisement

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

I have a simple JSON file sitting in a data folder within the source of my website. In a javascript script I want to read the JSON and update the DOM with the information inside. The file structure of my website is like this

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)

I obviously can’t use require() from nodejs because this is on the client side. I don’t see how FileReader would work here. All I need to do is read this JSON file from ../src/data/jsonFile.json.

Advertisement

Answer

I meant the third answer, you can use fetch statement. If you are confused about fetch then I recommend you look it up online first.

fetch("path/to/file")
  .then(response => response.json())
  .then(json => console.log(json));
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement