read from json file in javascript

To read from a JSON file in JavaScript, you need to use the fs module if working in Node.js. For web development, you can use asynchronous fetch method or XMLHttpRequest to get the data from the JSON file.

Here's an example of how to use fs in Node.js:

index.tsx
const fs = require('fs');

fs.readFile('path/to/file.json', 'utf8', function(err, data) {
  if (err) throw err;
  const json = JSON.parse(data);
  console.log(json);
});
170 chars
8 lines

This code will read the contents of the file located at "path/to/file.json", parse the JSON data using JSON.parse, and log it to the console.

If you want to use fetch method in web development, you can do something like this:

index.tsx
fetch('path/to/file.json')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));
136 chars
5 lines

This code will use the fetch API to retrieve the JSON file, convert the response to JSON using the json() method, and log it to the console.

gistlibby LogSnag