How to make Tyscript read a JSON file that is on disk?

Asked

Viewed 386 times

0

I have a code in Typescript (Nodejs-10.6.0) and need to create a variable that will recover the contents of a JSON file.

I have tried to import the contents from the file in the following ways:

 1. import { orderPayload } = require('../../events/qa/myfile.json');
 2. import { orderPayload } = '../../events/qa/myfile.json';
 3. const orderPayload: Order = require ('../../events/qa/myfile.json');
 4. const orderPayload= require ('../../events/qa/myfile.json');

Tslint shows the following errors:

 1. TS1141 - String Literal expected, Required statement not part of a import statement (no-var-required)
 2. String Literal expected
 3. Required statement not part of a import statement (no-var-required)
 4. Required statement not part of a import statement (no-var-required)

Is there any way to import the contents of this JSON file into the variable orderPayload without using the FS file system module of Nodejs?

  • the file JSON has a key with the name orderPayload?

  • No. Only has 2 keys 'Metadata' and 'payload'.

  • A question: what was the problem of using FS? I thought it was the most common way to upload files. By the way, since it is Node should have library ready to load JSON that uses FS internally, if you just want a cleaner code.

1 answer

1

You cannot simply import a JSON file without the proper Exports.

Do the following:

Myfile.json

export const orderPayload  = {...}

And then you can do import { orderPayload } from '../../events/qa/myfile.json';

  • I can spin: const orderPayload = require('.teste.json');

  • It’s ... I cheated wrong. It would be import { orderPayload } from '../../events/qa/myfile.json'; or const orderPayload = require('../../events/qa/myfile.json');

  • Actually it is not necessary to export objects if you import . json by choosing which items you want to work perfectly. consign is proof that it loads the . json without exporting them. I consist of importing several . json from database settings, cloud, etc.

  • The consign uses fs young man. The author of the question said: without using Fs.... Behold

Browser other questions tagged

You are not signed in. Login or sign up in order to post.