Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON parsed file returning string instead of Array in node/express

I am having trouble when trying to parse an empty (stringified) Array from a JSON file, instead of returning an empty array, I am getting a string.

My JSON file initial set up is:

"[]"

I am assigning the parsed data to a variable using File System

let parsedObjs = JSON.parse(fs.readFileSync(__dirname + '/data/employees.json'));

When I try this in a browser console, I get an empty array as I would expect:

JSON.parse("[]")
> []

However, in Node/Express I am getting a string returned:

console.log(type of:', typeof parsedObjs);
> type of: string

Bizarrely, if I set up initial file as an unstringified Array it returns an Array:

> []

But of course, this produces an 'Unexpected end of JSON' error.

I'm very new to this, please tell me what I'm doing wrong. Thank you.

EXTRA INFO

Function in it's entirety:

function populateSelectors(selector) {
  let foundOptions = [];
  let parsedObjs = JSON.parse(fs.readFileSync('./data/employees.json'));

  parsedObjs.forEach(obj => {
      let key = Object.keys(obj)[0];
      let optionName = obj[key][selector];
      if (foundOptions.indexOf(optionName) === -1 ) {
          foundOptions.push(optionName);
      }
  });
  return foundOptions;
}

ERROR in Full (I've obviously changed the full path to ):

SyntaxError: Unexpected end of JSON input
application.js:630
    at JSON.parse (<anonymous>)
    at Object.populateSelectors (<FULL PATH>\Rota Application 2\staff.js:14:27)
    at <FULL PATH>\Rota Application 2\app.js:45:28
    at Layer.handle [as handle_request] (<FULL PATH>\Rota Application 2\node_modules\express\lib\router\layer.js:95:5)
    at next (<FULL PATH>\Rota Application 2\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (<FULL PATH>\Rota Application 2\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (<FULL PATH>\Rota Application 2\node_modules\express\lib\router\layer.js:95:5)
    at <FULL PATH>\Rota Application 2\node_modules\express\lib\router\index.js:281:22

SOLVED!

The problem was I had a writeFile method elsewhere, they were both trying to access the file at the same time. I changed it to writeFileSync and problem solved!

like image 472
Cuckoo Avatar asked Aug 11 '26 06:08

Cuckoo


1 Answers

It's normal, the file is not in the right format, you must remove the quotation marks.

[]

JSON.parse("[]") works with quotation marks because you must pass a string to the parse function.

like image 160
Óscar Andreu Avatar answered Aug 13 '26 20:08

Óscar Andreu