skip to Main Content

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


  1. 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;

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search