Import JSON array from local file to Typescript array

Posted on February 27, 2022

The sample JSON file content (data.json):

[
  {
    "FirstName": "Joe",
    "UserId": 1
  },
  {
    "FirstName": "Jack",
    "UserId": 2
  }
]

Next, add appropriate resolveJsonModule entry to tsconfig.json entry

{
    "compilerOptions": {  
      "esModuleInterop": true
      "resolveJsonModule": true
    } 
}

Finally, import the data and access it using the below code.

import data from './data.json';

interface Person{
    FirstName: string,
    UserId: number,
}

const userArray:User[] = data as User[];
to join this conversation on Samprix.Already have an account? Sign in to comment
SPONSORS