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?

Write your answer…

3 answers

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);
}
Show all replies

@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')

Reply to this…

Hashnode is a friendly and inclusive dev community.
Come jump on the bandwagon!

  • 💬 Ask programming questions without being judged

  • 🧠 Stay in the loop and grow your knowledge

  • 🍕 More than 500K developers share programming wisdom here

  • ❤️ Support the growing dev community!

Create my profile

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

tried option 2 on systemjs loading, it works!

Reply to this…

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!http://foo.com/data_returns_json/";

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

Show all replies

Doesn't work for SystemJs :(

Reply to this…

Reza Razavipour's photo

Joined on

Sep 1, 2016

Welcome to Hashnode
the dev community

The programming forum to discuss topics broader than bugs and issues, write and share knowledge and connect with the best developers.