How to Import a JSON file in Typescript
Jasser Mark Arioste
Importing JSON files is a common practice in Node.js projects. In this short tutorial, you will learn how to statically import JSON files in Typescript.
I created a GitHub repo if you want to follow along with this tutorial. You can simply clone it and run `yarn dev`
Import a JSON file in Typescript #
Suppose you have a JSON file data/users.json
that contains user objects. To import this file in Typescript you have to do at least three steps:
- In
tsconfig.json
, set"esModuleInterop"
option totrue
. - In
tsconfig.json
, set"resolveJsonModule"
option totrue
. - Import the file using
import users from "./data/users.json"
Setting tsconfig.json
#
Make sure you've set esModuleInterop
and resolveJsonModule
to true as shown below:
// tsconfig.json { "compilerOptions": { // ... other options "esModuleInterop": true, "resolveJsonModule": true } }
1234567
Importing the JSON file. #
Assuming your file is located in ./data/users.json
, To import the file you can do the following:
// index.ts import users from "./data/users.json"
12
Also, make sure to use the correct relative path when importing. For example, if you're importing from "/components/some_component.ts"
you can do:
// components/some_component.ts import users from "../data/users.json" const user = users[0];
123
What about the typings? #
Normally, Typescript automatically infers the types from the JSON file. For example, our users.json
file records might look like this:
// data.users.json [{ "id": 1, "first_name": "Allayne", "last_name": "Wringe", "email": "awringe0@123-reg.co.uk", "gender": "Male", "ip_address": "217.119.220.86", "country": "CL" } ... ]
1234567891011
When we import the file, it automatically infers the type for us:
What if I want to use my own types? #
If you created your own types, it's still possible to use using the as
operator in typescript. For example:
// types/User.ts export interface User { first_name?: string; last_name?: string; id: number; email: string; gender: string; ip_address: string; country?: string; }
12345678910
Here's how to modify the inferred typings:
// index.ts import _users from "./data/users.json" import { User } from "./types/User"; const users = _users as User[]; const user = users[0]; console.log(user.first_name)
123456
And that's it.
Conclusion #
We learned how to statically import JSON files using the import statement in a TypeScript project.
If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on Twitter.
Resources #
- Typescript Config Docs
- Full Code Reference - https://github.com/jmarioste/typescript-json-import
Credits: Image by Trond Giæver Myhre from Pixabay