gpt4 book ai didi

javascript - 向 .json 文件添加另一个条目。 NodeJS

转载 作者:行者123 更新时间:2023-12-03 05:20:37 25 4
gpt4 key购买 nike

我正在使用 JSON 文件来存储一些数据,这是我当前的结构。由我的代码尝试创建。

 {
"Username": "ozziep",
"ProjectID": "ExpressJS",
"TimeStamp": "2016-12-30T19:54:52.418Z",
"Comments": "hello world how are we today?"
}

{
"Username": "alex",
"ProjectID": "Foo",
"TimeStamp": "2016-12-30T19:55:07.138Z",
"Comments": "we need to double check that this json system works. "
}

我是这样生成JSON的,不是最好的代码,还在学习JS。

var time = new Date();
var project_id = data.postid;
var comment = data.commentdata;
var usercommented = data.usercoment
fs.readFile("comments.json", 'utf-8', function(err, data) {
if (err) {
throw err;
}
if (typeof data !== "undefined") {
var jsongrid = {
"Username": usercommented,
"ProjectID": project_id,
"TimeStamp": time,
"Comments": comment
}
//this all works, for now. and will hopefully stay that way.
console.log(commentsdata)
var JSONStringed = JSON.stringify(jsongrid, null, 4) //turning the json grid into JSON, and prettyprinting it. generates correct JSON
var commentsdata = data; //current JSON on file.
var CompiledJSON = "\n"+commentsdata + "\n "+JSONStringed;//adding the new to the old.
var bCompiledJSON = "["+CompiledJSON+"\n]"
fs.truncate('comments.json', 0, function(){console.log('comments file can now be written to.')})



var time = new Date();
var project_id = data.postid;
var comment = data.commentdata;
var usercommented = data.usercoment
fs.readFile("comments.json", 'utf-8', function(err, data) {
if (err) {
throw err;
}
if (typeof data !== "undefined") {
var jsongrid = {
"Username": usercommented,
"ProjectID": project_id,
"TimeStamp": time,
"Comments": comment
}
//this all works, for now. and will hopefully stay that way.
console.log(commentsdata)
var JSONStringed = JSON.stringify(jsongrid, null, 4) //turning the json grid into JSON, and prettyprinting it. generates correct JSON
var commentsdata = data; //current JSON on file.
var CompiledJSON = "\n"+commentsdata + "\n "+JSONStringed;//adding the new to the old.
var bCompiledJSON = "["+CompiledJSON+"\n]"
fs.truncate('comments.json', 0, function(){console.log('comments file can now be written to.')})

// var jsonsearched = CompiledJSON.hasOwnProperty("Vortex.API")
console.log(CompiledJSON[2])
// var CompiledJsonPretty = JSON.stringify(CompiledJSON, null, 4); //pretty printing this creation.
console.log("A user has submitted a comment to post " + project_id) //logging.
console.log("Generating JSON")
console.log(CompiledJSON)
socket.emit("added_comment")

// var json_temp = {"Comments":{"Username":usercommented,"CommentData":comment,"date":time,"ProjectID":project_id}}
//var jsondata = JSON.stringify(json_temp)


console.log("--------------------------------------------")
console.log("Temp JSON generated - value: \n\n" + JSONStringed)
if (typeof JSONStringed !== "undefined") {
fs.writeFile("comments.json", bCompiledJSON, function(err) {
if (!err) {
//verify data has been written, cause comments are important!
fs.readFile("comments.json", 'utf-8', function(err, data) {
if (err) {
throw err;
}
if (data !== CompiledJSON) {
console.log("Writing comment JSON to file failed.")
console.log("- \n if (data) !== JSONStringed; failed. ")
} else{
socket.emit("added_comment")
}
})
} else {
throw err;
}
})
}
}
})
// console.log(JSON.stringify(json))
})

我确实计划将其最小化一点,对于如此简单的事情来说,代码太多了,无论如何,它都会从 jsongrid 写入文件创建 JSON,但唯一的问题是它将它们写在彼此之上,如下所示如上所示,这不起作用,因为我无法按名称或其他方式挑选出一个 block ,我尝试读取文件,删除它,向其中添加 [] ,然后写入JSON 再次文件,但这只是添加了很多 [] 周围,这也不起作用,我想访问 JSON 中的数据,例如 foo[1].Username 例如。实现这一目标的最佳方法是什么?

最佳答案

最简单的解决方案是在文件中存储 JSON 对象数组。

请记住,虽然 JSON 代表“JavaScript 对象表示法”,但数组也是有效的 JSON。所以你的文件可能如下所示:

[
{
"Username": "ozziep",
"ProjectID": "ExpressJS",
"TimeStamp": "2016-12-30T19:54:52.418Z",
"Comments": "hello world how are we today?"
},
{
"Username": "alex",
"ProjectID": "Foo",
"TimeStamp": "2016-12-30T19:55:07.138Z",
"Comments": "we need to double check that this json system works. "
}
]

然后,要在文件中添加、删除、查找对象,您可以读取整个文件,解析它,然后执行您需要的操作。

添加评论:

var time = new Date();
var project_id = data.postid;
var comment = data.commentdata;
var usercommented = data.usercoment
// Read in whole file
fs.readFile("comments.json", 'utf-8', function(err, data) {
if (err) {
throw err;
}
if (typeof data !== "undefined") {
// Parse the current contents of the file into array
var currentComments = JSON.parse(data);

// Create our new comment
var newComment = {
"Username": usercommented,
"ProjectID": project_id,
"TimeStamp": time,
"Comments": comment
};

// Push it onto the end of the existing comments
currentComments.push(newComment);

// Convert comments back to string to be written
var stringifiedComments = JSON.stringify(currentComments);

// Write back to file!
fs.writeFile("comments.json", stringifiedComments, function (err) {
console.log(err);
});
}
}

关于javascript - 向 .json 文件添加另一个条目。 NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41402389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com