Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use a json file in a typescript file

I have a file called men.json.

I want to do the equivalent of var men = require('./men.json');.

Whatever I have tried it looks for ./men.json.js file.

I read that I can not use import since it is not a ts file.

What is the equivalent required line?

like image 272
reza Avatar asked Dec 29 '16 02:12

reza


People also ask

Can you use json in TypeScript?

The TypeScript comes up with the functionality of working with JSON Type data. JSON being the JavaScript Object Notation, is used to make a data model that is easy to write and read. We can easily analyze large and complex data set with this TypeScript JSON type.

How do you read a json response in TypeScript?

Use the JSON. parse() method to parse a JSON string in TypeScript, e.g. const result: Person = JSON. parse(jsonStr) . The method parses a JSON string and returns the corresponding value.


1 Answers

declare module '*.json' {
    var _: any;
    export default _;
}

then you can import mem from './mem.josn'

put this into some file that's included in tsconfig.json

now you can require .json, this works for any other file formats (though you need webpack since nodejs cannot require them directly)

like image 64
Qiaosen Huang Avatar answered Oct 05 '22 04:10

Qiaosen Huang