[英]NodeJS: Pulling data from JSON,modifying and Sending object back to the same JSON file
JSON、NodeJs 等的新手。
我希望做的是將以下 JSON 文件數據接收到 NodeJS(和 Angular)項目修改接收到的數據,然后將其發送回 JSON 文件。
JSON 文件:
{
"groups":{
"groupid": [1,2,3],
"name": ["g1","g2","g3"]
},
"rooms": {
"room1": {
"roomid": 1,
"pGroup": ["g1","g2","g3"]
},
"room2": {
"roomid": 2,
"pGroup": ["g3"]
},
"room3": {
"roomid": 3,
"pGroup": ["g1","g2"]
}
}
}
我可以通過執行以下操作來接收和存儲數據:
// Load in groups from groups.json
fs.readFile('./data/groups.json', 'utf8', function(err, data){
if (err) throw err;
groups = [];
let gArray = [];
gArray = JSON.parse(data);
console.log(gArray.groups.name[1]);
for(let i = 0; i < gArray.groups.name.length; i++){
groups.push(gArray.groups.name[i]);
}
});
我目前用於存儲數據的內容:
groups.push(newgroup);
//store room in JSON file
let groupString = JSON.stringify(groups);
fs.writeFile('data/groups.json', groupString, 'utf-8', function(err){
if (err) throw err;
});
我知道上面將它放入一個字符串並存儲數組,但我嘗試尋找一種替代方法,我可以在其中編輯我需要的 JSON 文件的部分,但我無法在任何地方找到答案。
任何幫助都將不勝感激。
謝謝
為了編輯文件的內容,您需要實際寫入文件
You can always just edit the properties of the json and keep the JavaScript object in memory ok the nodeJS application and if it's a server just send The memory -stored object to the client directly, do it looks like the file was updated when it really wasn 't,但是當服務器關閉時,不會保存未寫入磁盤的更改
如果要保存進度,則必須寫入磁盤(或某種數據庫等)
編輯
但仍有一種方法可以做你想做的事,實際上他有很多數據庫工作,但對於 json 它可能有點復雜
基本上,節點中的 function 一次只能讀取文件的特定字節
https://stackoverflow.com/a/23720178/2016831
但真正的方法是使用 fs.open 然后 fs.write(look it up) 讀取/寫入文件的特定字節索引
問題是你怎么知道要寫入文件的哪些索引,這是一門關於數據庫如何工作等的完整科學,通常二進制更容易,因為它被分成不同的塊,每個塊都有一些 header 字節,這些字節指的是之前和之后的塊等然后你需要讀取一個根塊,它告訴你要讀取的Uther塊讀取等等,直到你找到你為什么要編輯的部分,然后在你這樣做之后你需要更新一些其他塊,或者有時不一定等查找如何從頭開始制作數據庫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.