简体   繁体   中英

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!

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.

By Best guess as to what is happening:

If you store your empty array as "[]" in your file, when you read it in node JS, the string seen by the parse will look like this: "\\"[]\\"" .

So as far as the parser is concerned, it is parsing a string and returns the string. (Like doing JSON.parse('\\"[]\\"'); )

Any file read by readFile WILL BE A STRING. So it is sufficient to keep your empty array as [] without the quotes in your JSON file

I got the same issue, then I realize the mistake. I stringify a string "[]" instead an object []

在此处输入图片说明

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM