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
.
2
Answers
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.In order to be able to read that JSON object data you will need to parse it to the object:
Now you can read/access everything from
serverConfigs
;A JSON module is equivalent to an ES6 module with default export.
The line
imports the JSON module into
config.default
. You can either log it withor import the default export with
and log with
More info about JSON import: https://v8.dev/features/import-assertions