简体   繁体   English

如何使用Node.js和Socket.io将键+值写入JSON文件

[英]How to write key + values to a JSON file with Node.js and Socket.io

I am working on a scoreboard with Socket.io and Node.js . 我正在使用Socket.io和Node.js制作记分牌。 Now I would like to save the scores of the participants into a JSON file. 现在,我想将参与者的分数保存到JSON文件中。

This is what I tried to do: 这是我尝试做的:

socket.on('part score', function(name, score){
    let jdata = fs.readFileSync('participants.json');
    let json = JSON.parse(jdata);
console.log(name, score);
//outputs: foo 10

    fs.writeFile('participants.json', JSON.stringify(json.jury1.push({name: score}, null, 2)), function(){
        console.log("name added: "+name+" value added: "+score);
    }); 
});

How my JSON file looks like: 我的JSON文件如下所示:

{"jury1": []}

When I executed to code above my JSON files turns into "3" when the score is 10. Also everything in my JSON file is gone after execution. 当我在上面的代码中执行代码时,得分为10时,JSON文件变成“ 3”。执行后,JSON文件中的所有内容也消失了。

How do I properly add the key+value into my Jury1? 如何将键+值正确添加到Jury1中? Thanks already! 已经谢谢你了!
ps: name and score gets send through the client sided script ps:名称和分数通过客户端脚本发送

Jury1 is an array? Jury1是一个数组吗?

I think that you should parse all the data that you want so instead of doing: 我认为您应该解析所需的所有数据,而不要这样做:

JSON.stringify(json.jury1.push({name: score}, null, 2)

try something like: 尝试类似:

jury1 with the score you need var data = JSON.stringify(jury1)

You already have a json file. 您已经有一个json文件。 Why are you doing a JSON.parse again ? 为什么还要再次执行JSON.parse? I suspect that is the issue. 我怀疑这是问题所在。 can you try to print the content of json.jury1 to confirm the same ? 您可以尝试打印json.jury1的内容以确认相同吗?

Also, check the result from fs.writeFile() if there is any err 另外,检查fs.writeFile()的结果是否有错误

fs.writeFile('participants.json', JSON.stringify(json.jury1.push({name: score}, null, 2)), function(err){
    console.log(err, "name added: "+name+" value added: "+score);
});

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

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