Home > Software design >  ES6 import of JSON returns 'undefined'
ES6 import of JSON returns 'undefined'

Time:01-18

When I want to import JSON into my Node application following es6 like this:

import * as config from "./server-config.json" assert {type: 'json'}

When I try to use the imported values like this

console.log(config["url"])

It will just return the value undefined. I am having this problem using Node 19, the path is correct, the json is correct and even if I use --experimental-json-modules it will return an undefined.

CodePudding user response:

A JSON module is equivalent to an ES6 module with default export.

The line

import * as config from "./server-config.json" assert {type: 'json'}

imports the JSON module into config.default. You can either log it with

console.log(config.default["url"])

or import the default export with

import config from "./server-config.json" assert {type: 'json'}

and log with

console.log(config["url"])

More info about JSON import: https://v8.dev/features/import-assertions

CodePudding user response:

If there were several functions/objects/arrays/consts were exported in one file and you wanted to import them all as a single object in that case import * as everything from "./moduleLocation" would be correct.

In your case, there is a single JSON object in the server-config.json file located in the project root. Therefore, it would be appropriate to import that JSON object, if it was exported, as a single object.

import config from "./server-config.json";

In order to be able to read that JSON object data you will need to parse it to the object:

const serverConfigs = JSON.parse(config);

Now you can read/access everything from serverConfigs;

  • Related