user7789076
user7789076

Reputation: 798

Import json in typescript

I am new to typescript.In my project we are using typescript2, In one of my requirement i need to import json file. so i have created .d.ts file as follows

 test.d.ts
declare module "*.json" {
    const value: any;
    export default value;
}

i have included this definition in my tsconfig.json and importing to my ts file as follows

  test.ts
//<refrence path="./test.json"/>
import * as data from './test.json';

when i am building my code i am getting following error

Cannot find module './test.json'

Note:- i don't want to use Requirejs

Thanks

Upvotes: 5

Views: 17556

Answers (3)

kentor
kentor

Reputation: 18504

With TypeScript 2.9.+ you can simply import JSON files with typesafety and intellisense like this:

import testJson from './test.json';
console.log(testJson.yourPropertyName);

Make sure to add these settings to your tsconfig.json:

"resolveJsonModule": true,
"esModuleInterop": true,

If you need the data to be recognised as a specific class, you can do that after import with as, for instance:

const typedData = testJson as MyType[]

Upvotes: 19

Ferie
Ferie

Reputation: 1436

Following this great article and depending on the TypeScript version you are using, you can follow the other 2 answers.

The case that is missing from them is when you are using TypeScript 2+. In this case, if you have a json file like this:

{
    "name": "testing"
}

you should add the following in the typings.d.ts file:

declare module "*.json" {
    const value: any;
    export default value;
}

And then import the json file as follows:

import * as data from './example.json';

const word = (<any>data).name;

console.log(word); // output 'testing'

Upvotes: 1

zelda11
zelda11

Reputation: 423

I handled that using a .ts with the json data in a variable:

import { data } from './jsonData'; // jsonData.ts

And the jsonData.ts would be like that:

export var data = {
  "key": "value",
  "key2": "value2"
}

Upvotes: 2

Related Questions