Home > Software engineering >  Object loaded from json file has its values assigned to a property called default
Object loaded from json file has its values assigned to a property called default

Time:10-14

In my node TypeScript project, I have a json file with some default config. Let's say it looks like this:

{
  prop1: 123,
  prop2: 123
}

And I'm loading values from this file somewhere along the way like this:

import * as defconfig from '../configuration/config.json';

And when I'm checking it in the console I see this output:

{
  prop1: [Getter],
  prop2: [Getter],
    default: {
      prop1: 123,
      prop2: 123
   }
}

And also if I try to override this object with spread operator or Object.assign, the result is following:

const options = {
  prop1: 321,
  prop2: 321
};

console.log({...defconfig, ...options});

//OR

console.log(Object.assign(defconfing, options));

//produces

{
  prop1: 321,
  prop2: 321,
  default: {
    prop1: 123,
    prop2: 123
  }
}

Can anyone explain where is the default coming from and how to get rid of it?

The same code works perfectly fine when not using .json file but defining config with a normal object, but the issue is that I have to use the file.

CodePudding user response:

According to the latest node versions, JSON files cannot be read directly as modules. Unless you use --experimental-json-modules flag while running.

A solution would be to use commonjs (for that you would need to change file extension to .cjs) method require which will be able to do the task or you can use fs module to read JSON string and then parse.

  • Related