简体   繁体   English

Javascript Node.js JSON.parse数组

[英]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. 我正在上关于udemy的课程,我真的很困惑当notes = JSON.parse(notesString)假定是对象(对吗?)时如何将其作为数组(因为JSON.parse使其成为对象)。

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. 那里需要JSON.parse(),因为fs操作的输出是一个字符串,我们需要将其转换为对象才能正确访问它。 The data inside it is a JSON Array as a result we are able read it. 其中的数据是JSON数组,因此我们可以读取它。 Add try catch around the JSON.parse because if the data is not of JSON type then it will cause an error. 在JSON.parse周围添加try catch,因为如果数据不是JSON类型,则将导致错误。

If JSON in file notes-data.json contains JSON-array, ie some content like 如果文件notes-data.json中的JSON包含JSON数组,即某些内容,例如

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

You will get array from JSON.parse method. 您将从JSON.parse方法获取数组。

If JSON in file notes-data.json contains JSON-array, ie some content like 如果文件notes-data.json中的JSON包含JSON数组,即某些内容,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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