How to import JSON data in Nextjs with TS Type
Nextjs is a powerful Reactjs framework which has a good developer experience. In this post I like to show you how to import JSON data file into the Nextjs project with Typescript Type.
JSON Data
Usually, JSON data file contains set of objects which serve as the data for your application. We need not rely on any library for importing data in you Nextjs file, all it take is a import statement.
import data from ''jsonpath/data.json"TypeScript Type and JSON
We may want our imported data is typed. I have some type declared. Remember type and keys should match, i.e, if the key in the JSON is {country:'India' } and in the Typescript it should be {country:string}
Type
export type People{
name:string;
country:string;
}
Our JSON Data in File
[{name:'Manoj',country:'India'},
...
]
Import and casting the JSON
import data from ''jsonpath/data.json"const peoples = data as People[]
Comments
Post a Comment