5

I have the following jsondata.json file:

{
    "name": "John",
    "age": 30,
    "car": "ferrari"
}

In the same directory, I have a typescript file main.ts where I simply congole.log the json from the jsondata.json

import * as j from './jsondata.json';

console.log(j);

The result is surprising:

{
  name: 'John',
  age: 30,
  car: 'ferrari',
  default: { name: 'John', age: 30, car: 'ferrari' }
}

What is that default field? Why does it appear, and how can I get rid of it?


For reference, this is my tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "sourceMap": true,
    "outDir": "./out",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "forceConsistentCasingInFileNames": true
  }
}
Atharva Shukla
  • 2,098
  • 8
  • 21

1 Answers1

5

I tried some combinations of the settings and found that the last two settings are the required behavior.

jsondata.json:

{
    "name": "John",
    "age": 30,
    "car": "ferrari2"
}

resolveJsonModule set to true and no esModuleInterop and import with no * import causes error.

main.ts:

import j from './jsondata.json';
console.log(j);

tsconfig.ts:

"resolveJsonModule": true,
// "esModuleInterop": true

result:

>

{ name: 'John', age: 30, car: 'ferrari2' }

Module ... can only be default-imported using the 'esModuleInterop' flag

Both flags are set to true and * import shows default

main.ts:

import * as j from './jsondata.json';
console.log(j);

tsconfig.ts

"resolveJsonModule": true,
"esModuleInterop": true

result:

>

{
  name: 'John',
  age: 30,
  car: 'ferrari2',
  default: { name: 'John', age: 30, car: 'ferrari2' }
}

Both flags set to true with no * import does not show default

main.ts:

import j from './jsondata.json';
console.log(j);

tsconfig.ts:

"resolveJsonModule": true,
"esModuleInterop": true

result:

>

{ name: 'John', age: 30, car: 'ferrari2' }

resolveJsonModule set too true and no esModuleInterop and * import shows no default

main.ts:

import * as j from './jsondata.json';
console.log(j);

tsconfig.ts:

"resolveJsonModule": true,
// "esModuleInterop": true

result:

>

{ name: 'John', age: 30, car: 'ferrari2' }

Atharva Shukla
  • 2,098
  • 8
  • 21
  • 1
    See [this answer](https://stackoverflow.com/questions/49996456/importing-json-file-in-typescript) for a way to do this using types in typescript. The fact to declare a generic json module in typings.d.ts removes the `default` property from the imported json file. – sebastienhamel Aug 06 '21 at 15:20