Introduction to TypeScript JSON type. The TypeScript comes up with the functionality of working with JSON Type data. JSON being the JavaScript Object Notation, is used to make a data model that is easy to write and read. We can easily analyze large and complex data set with this TypeScript JSON type.
Make sure the type attribute on the script tag is set to module . Use an import assertion to import the JSON file. For example, import myJson from './example.
Use the fetch() Function to Load JSON Files in JavaScript This function fetches the file from the path where it is saved and then returns the file as the response in the console. data . This function is only suitable for working in the web-based environment as the fetch API works only in that environment.
Aonepathan's one-liner was working for me until a recent typescript update.
I found Jecelyn Yeen's post which suggests posting this snippet into your TS Definition file
add file typings.d.ts
to the project's root folder with below content
declare module "*.json" {
const value: any;
export default value;
}
and then import your data like this:
import * as data from './example.json';
Typescript 2.9 (docs) introduced a better, smarter solution. Steps:
resolveJsonModule
support with this line in your tsconfig.json
file: "compilerOptions": {
...
"resolveJsonModule": true
}
the import statement can now assumes a default export:
import data from './example.json';
and intellisense will now check the json file to see whether you can use Array etc. methods. pretty cool.
As stated in this reddit post, after Angular 7, you can simplify things to these 2 steps:
compilerOptions
in your tsconfig.json
file:"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
import myData from '../assets/data/my-data.json';
And that's it. You can now use myData
in your components/services.
Here is complete answer for Angular 6+ based on @ryanrain answer:
From angular-cli doc, json can be considered as assets and accessed from standard import without use of ajax request.
Let's suppose you add your json files into "your-json-dir" directory:
add "your-json-dir" into angular.json file (:
"assets": [
"src/assets",
"src/your-json-dir"
]
create or edit typings.d.ts file (at your project root) and add the following content:
declare module "*.json" {
const value: any;
export default value;
}
This will allow import of ".json" modules without typescript error.
in your controller/service/anything else file, simply import the file by using this relative path:
import * as myJson from 'your-json-dir/your-json-file.json';
Thanks for the input guys, I was able to find the fix, I added and defined the json on top of the app.component.ts file:
var json = require('./[yourFileNameHere].json');
This ultimately produced the markers and is a simple line of code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With