create a json file in typescript

To create a JSON file in TypeScript, you need to follow these steps:

  1. Define the JSON object with the required properties.
index.ts
const data = {
  name: 'John Doe',
  age: 30,
  email: 'johndoe@example.com'
};
80 chars
6 lines
  1. Convert the object to a JSON string.
index.ts
const jsonData = JSON.stringify(data);
39 chars
2 lines
  1. Use Node.js to write the JSON string to a file.
index.ts
import * as fs from 'fs';

fs.writeFileSync('data.json', jsonData);
68 chars
4 lines

The writeFileSync method synchronously writes the jsonData string to a file named data.json.

The complete TypeScript code would look like this:

index.ts
import * as fs from 'fs';

const data = {
  name: 'John Doe',
  age: 30,
  email: 'johndoe@example.com'
};

const jsonData = JSON.stringify(data);
fs.writeFileSync('data.json', jsonData);
188 chars
11 lines

gistlibby LogSnag