[json] How to import JSON File into a TypeScript file?

I am building a map application using Angular Maps and want to import a JSON file as a list of markers defining locations. I'm hoping to use this JSON file as marker[] array inside the app.component.ts . Instead of defining a hardcoded array of markers inside the TypeScript file.

What is the best process of importing this JSON file for use in my project? Any direction greatly appreciated!

This question is related to json angular google-maps typescript maps

The answer is


For Angular 7+,

1) add a file "typings.d.ts" to the project's root folder (e.g., src/typings.d.ts):

declare module "*.json" {
    const value: any;
    export default value;
}

2) import and access JSON data either:

import * as data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
    constructor() {
        console.log(data.default);
    }

}

or:

import data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
    constructor() {
        console.log(data);
    }

}

Angular 10

You should now edit the tsconfig.app.json (notice the "app" in the name) file instead.

There you'll find the compilerOptions, and you simply add resolveJsonModule: true.

So, for example, the file in a brand new project should look like this:

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [],
    "resolveJsonModule": true
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

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:

  1. add "your-json-dir" into angular.json file (:

    "assets": [ "src/assets", "src/your-json-dir" ]

  2. 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.

  3. 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.


let fs = require('fs');
let markers;
fs.readFile('./markers.json', handleJSONFile);

var handleJSONFile = function (err, data) {
   if (err) {
      throw err;
   }
   markers= JSON.parse(data);
 }

In angular7, I simply used

let routesObject = require('./routes.json');

My routes.json file looks like this

{

    "routeEmployeeList":    "employee-list",
    "routeEmployeeDetail":      "employee/:id"
}

You access json items using

routesObject.routeEmployeeList

As stated in this reddit post, after Angular 7, you can simplify things to these 2 steps:

  1. Add those three lines to compilerOptions in your tsconfig.json file:
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
  1. Import your json data:
import myData from '../assets/data/my-data.json';

And that's it. You can now use myDatain your components/services.


As of Typescript 2.9, one can simply add:

"compilerOptions": {
    "resolveJsonModule": true
}

to the tsconfig.json. Thereafter, it's easy to use a json file (and there will be nice type inference in VSCode, too):

data.json:

{
    "cases": [
        {
            "foo": "bar"
        }
    ]
}

In your Typescript file:

import { cases } from './data.json';


I couldn't import a different file.json too. But I resolved it like this

const swaggerDoc = require('../swagger.json')

I had read some of the responses and they didn't seem to work for me. I am using Typescript 2.9.2, Angular 6 and trying to import JSON in a Jasmine Unit Test. This is what did the trick for me.

Add:

"resolveJsonModule": true,

To tsconfig.json

Import like:

import * as nameOfJson from 'path/to/file.json';

Stop ng test, start again.

Reference: https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/#json-imports


First solution - simply change the extension of your .json file to .ts and add export default at the beginning of the file, like so:

export default {
   property: value;
}

Then you can just simply import the file without the need to add typings, like so:

import data from 'data';

Second solution get the json via HttpClient.

Inject HttpClient into your component, like so:

export class AppComponent  {
  constructor(public http: HttpClient) {}
}

and then use this code:

this.http.get('/your.json').subscribe(data => {
  this.results = data;
});

https://angular.io/guide/http

This solution has one clear adventage over other solutions provided here - it doesn't require you to rebuild entire application if your json will change (it's loaded dynamically from a separate file, so you can modify only that file).


Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to google-maps

GoogleMaps API KEY for testing Google Maps shows "For development purposes only" java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion How to import JSON File into a TypeScript file? Googlemaps API Key for Localhost Getting "Cannot call a class as a function" in my React Project ERROR: Google Maps API error: MissingKeyMapError This page didn't load Google Maps correctly. See the JavaScript console for technical details Google Maps API warning: NoApiKeys ApiNotActivatedMapError for simple html page using google-places-api

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to maps

How to import JSON File into a TypeScript file? Iterating over Typescript Map How can I enter latitude and longitude in Google Maps? Importing CSV File to Google Maps Accessing the last entry in a Map Dynamically add data to a javascript map Get the distance between two geo points Openstreetmap: embedding map in webpage (like Google Maps) What is the ideal data type to use when storing latitude / longitude in a MySQL database? Calculate distance between two latitude-longitude points? (Haversine formula)