fetch from json file code example

Example 1: fetch response json or text

const _fetch = async props => {
   const { endpoint, options } = props
   return await fetch(endpoint, options)
   .then(async res => {
      if (res.ok) {
         return await res.clone().json().catch(() => res.text())
      }
      return false
   })
   .catch(err => {
      console.error("api", "_fetch", "err", err)
      return false
   })
}

Example 2: fetch json file

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

Example 3: how to fetch local json file in javascript

Try to use file system. Don't think reading from a JSON file works like that.

const fs = require('fs');
const json_data = require('../services/contributors.JSON');

fs.readFile(json_data, 'utf8', function (err, data) {
  try {
    data = JSON.parse(data)
    for (let i in data){
    console.log('Name:',data[i].name)
    }
  } catch (e) {
    // Catch error in case file doesn't exist or isn't valid JSON
  }
});