如何将数据追加到JSON数组

时间:2020-11-09 02:08:07

标签: javascript node.js json

我正在尝试为discord.js创建一个惩罚系统,在该系统中,当用户受到惩罚时,discord机器人会将其记录在json文件中。惩罚看起来像这样:

{
  "username": "baduser#4567",
  "id": "baduser's id",
  "type": "Mute",
  "time": "<time>",
  "issued_by": "username: Admin#1234 id: admin id"
}

在我的刑罚.js文件上附加第二个刑罚后,它会给我这样的东西:

{
  "username": "baduser#4567",
  "id": "baduser's id",
  "type": "Mute",
  "time": "<time>",
  "issued_by": "username: Admin#1234 id: admin id"
}{
  "username": "baduser#4567",
  "id": "baduser's id",
  "type": "Mute",
  "time": "<time>",
  "issued_by": "username: Admin#1234 id: admin id"
}

并且在两种惩罚之间显然存在“文件预期结束”错误。 我已经尝试过在线浏览各种文档,但是这些文档都不符合我的最终目标,因为刑罚json文件看起来像这样:

{
  "punishments": [{
    "username": "baduser#4567",
    "id": "baduser's id",
    "type": "Mute",
    "time": "<time>",
    "issued_by": "username: Admin#1234 id: admin id"
  }, {
    "username": "baduser#4567",
    "id": "baduser's id",
    "type": "Mute",
    "time": "<time>",
    "issued_by": "username: Admin#1234 id: admin id"
  }]
}

TL; DR我需要一种将这些惩罚添加到数组中的方法,最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

var jsonObj = {
  "punishments": [
    {
    "username": "baduser#4567",
    "id": "baduser's id",
    "type": "Mute",
    "time": "<time>",
    "issued_by": "username: Admin#1234 id: admin id"
  }
]
}

var newPunish = {
    "username": "baduser#4567",
    "id": "baduser's id",
    "type": "Mute",
    "time": "<time>",
    "issued_by": "username: Admin#1234 id: admin id"
  }

jsonObj['punishments'].push(newPunish)