简体   繁体   中英

Javascript nodejs JSON.parse array

I'm taking a course on udemy and i'm really confused on how notes = JSON.parse(notesString) is an array when it's suppose to be an object (right?) since JSON.parse makes it an object.

var addNote = (title, body) => {
  var notes = []; // Create empty array
  var note = { // Fetch user input
    title,
    body
  };
  try {
    var notesString = fs.readFileSync("notes-data.json"); //  Get current notes
    notes = JSON.parse(notesString); // convert current notes into object
    console.log("try:", notes.constructor)
  }catch(e){

  }
  console.log(notes)
  notes.push(note);
  fs.writeFileSync("notes-data.json", JSON.stringify(notes));
};

JSON.parse() is required over there because the output of a fs operation is a string which we need to convert into an object in order to access it properly. The data inside it is a JSON Array as a result we are able read it. Add try catch around the JSON.parse because if the data is not of JSON type then it will cause an error.

If JSON in file notes-data.json contains JSON-array, ie some content like

[{"one":1}, {"two":2}]

You will get array from JSON.parse method.

If JSON in file notes-data.json contains JSON-array, ie some content like

var data = "[{"one":1}, {"two":2}]";
var result = JSON.parse(data);
console.log(result)

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