2

I'm trying to read an external JSON file in NodeJS, but its returning undefined at the start of the JSON. I'm using readFileSync since this is a config file, and this process needs to be completed first before moving on.

NOTE: There is NO white space at the top of the external file.

EXTERNAL JSON FILE

{
   email:{
       username: "someUserName",
       password: "somePassword"
   },
   database: {
      username: "databaseUser",
      password:"datbasePassword"
   }
}

NODE JS

"use strict";

const fs = require("fs");
let rawData = fs.readFileSync("/run/secrets/secrets_file.json");
let secrets= JSON.parse(rawData);

console.log("SECRETS: ", secrets);

RETURNS

undefined:1
data = {

SyntaxError: Unexpected token d in JSON at position 0
    at JSON.parse (<anonymous>)

What's happening here?

4
  • 2
    Validate your JSON. It's invalid. You need to double-quote the keys as well as the values. Commented Mar 4, 2021 at 17:16
  • Thanks @jarmod - I'm too use to writing objects, not JSON. Thank you. Commented Mar 4, 2021 at 17:20
  • Most modern programming editors with lint highlight the issues which is a good way to detect them. Commented Mar 4, 2021 at 17:24
  • also note that if you need to read the file only one you can just use the require way of loading a JSON file. Subsequent calls to the same require will return from cache. Commented Mar 4, 2021 at 17:56

2 Answers 2

3

Your JSON file is not valid JSON. You need to quote the keys.

{
    "email": {
        "username": "someUserName",
        "password": "somePassword"
    },
    "database": {
       "username": "databaseUser",
       "password": "datbasePassword"
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Have you check And key "d" in json which is not visible in the front of screen. that may written by mistake some where else in the file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.