How to use a JSON file in TypeScript?

I have a file called men.json. I want to do the equivalent of var men = require('./men.json');

Whatever I have tried, it is looking for a ./men.json.js file. I read that I can not use import since it is not a .ts file

What is the equivalent of the require line?

Sai Kishore Komanduri's photo

require is meant for loading your modules; the recommended way to load files (including the JSON ones) is through Node's filesystem module.

You could do something like this:

// Declare your variables
var fs = require('fs');
var menObject;

// Read the file, and pass it to your callback
fs.readFile('./men.json, handleJSONFile);

// Handle the data 
var handleJSONFile = function (err, data) {
    if (err) {
        throw err;
    menObject = JSON.parse(data);
Reza Razavipour's photo

when I run the above code, this is Angular 2 project I need to mention, I still get zone.js:1382 GET http://localhost:3000/node_modules/fs.js 404 (Not Found)

Any ideas, where this is coming from?

Sai Kishore Komanduri's photo

Engineering an eGovernance Product | Hashnode Alumnus | I love pixel art

@rezarazavipour I have not worked with Angular 2, but it seems you are using System.js for loading the modules; this presumption is based on a quick search of your error, which has brought up the following solution:

System.js overrides Node.js's require method and uses it's own resolution mechanism. So instead of using require, you would use System._nodeRequire('fs')

Al Dass's photo

Thanks to TypeScript 2.x Wildcard Module Declarations you can do the following:

Somewhere in a *.d.ts file add this (or check if its already there):

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

Then you can do things like this in your TypeScript code:

import * as data1 from './data/some.json';
import data2 from "json!";

Note: I think this is already part of the ES6/ES2015 standard if you're writing plain JS targeting ES6/ES2015.

Porfirio Chávez's photo

Doesn't work for TSDoc :(

Ken Han's photo

IT Professional

Doesn't work for SystemJs :(

Balaji Venkiteswaran's photo

You can import only .ts or .tsx file using typescript imports

This can be done in two ways: a)if you want to import JSON you may have to use "require"

b) Copy the json and assign the JSON to a varaible and store it in a .ts file . In this case the variable will hold the json object . You can now import this .ts file using typescript type of imports and start using the object

Ken Han's photo

IT Professional

tried option 2 on systemjs loading, it works!