How to import JSON from a file in TypeScript

Published by admin on

TypeScript import JSON from a file

Import JSON from a file in TypeScript projects :

Suppose you need to work with a local json file in your typescript project. You have this file in your project folder, but how to import it? It is actually pretty easy. In this post, I will show you two different ways to import one JSON file in a typescript project.

 

Use require :

Suppose, we have one JSON file data.json on the root folder of a typescript project.

{
    "one": 1,
    "two": 2,
    "three": "3",
    "four": 4,
    "others": [
        {
            "five": 5
        }
    ]
}

Now, let’s say you have your main typescript file App.ts in that same folder. If you want the content of this JSON file in this ts file, you can use require as like below :

const data = require('./data.json')

It will convert the content of the data.json to a JavaScript object. You can access the values in these objects using the keys like data.one, data.two etc.

 

Use import :

You can use import. But it is a little bit different than Javascript import. Inside tsconfig.json, you need to add the below key-value pairs inside compilerOptions:

 "compilerOptions": {
        "resolveJsonModule" : true,
    }

resolveJsonModule was introduced in typescript 2.9. It allows importing JSON files directly in a typescript file.

Once you have added this flag, you can import JSON files in any typescript file in the project like below :

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

That’s it.

Categories: typescript

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *