Search code examples
jsontypescript

How to remove mysterious "default" field added to JSON?


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
  }
}

Solution

  • 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' }