read json from a file in typescript

To read a JSON file in TypeScript, you can use the built-in fs (file system) module in Node.js. Here is an example:

index.ts
import fs from 'fs';

// define the path to the JSON file
const filePath = './data.json';

// read the contents of the file
const fileContents = fs.readFileSync(filePath, 'utf-8');

// parse the JSON string to a JavaScript object
const data = JSON.parse(fileContents);

// now you can access your JSON data as a regular JavaScript object
console.log(data);
357 chars
14 lines

In this example, we are first importing the fs module. We then define the path to our JSON file using a relative file path. We then use the readFileSync method of fs to read the contents of the file. We pass in the file path and a character encoding (in this case 'utf-8') as arguments to readFileSync.

The result of readFileSync is a string containing the JSON data. We then use JSON.parse to parse the string into a JavaScript object.

Finally, we can access our JSON data as a regular JavaScript object and log it to the console.

Note that you may want to handle errors when reading the file using try/catch blocks.

gistlibby LogSnag