简体   繁体   English

如何将数据附加到 JSON 数组

[英]How to append data to a JSON array

I am trying to create a punishment system for discord.js where when a user is punished the discord bot logs it in a json file.我正在尝试为 discord.js 创建一个惩罚系统,当用户受到惩罚时,discord bot 将其记录在 json 文件中。 The punishment looks something like this:惩罚看起来像这样:

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

upon appending a second punishment to my punishments.js file it gives me something like this:将第二个惩罚附加到我的惩罚.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"
}

and obviously there is an "end of file expected" error between the two punishments.很明显,这两种惩罚之间存在“预期文件结束”错误。 I've tried looking through various documentation online but none of it quite fits my end goal which would be for the punishments.json file to look like this:我试过在网上浏览各种文档,但没有一个完全符合我的最终目标,即惩罚.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 i need a way to append these punishments inside an array, what would be the best way to go about this? TL; DR 我需要一种方法将这些惩罚附加到数组中,解决这个问题的最佳方法是什么?

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)

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

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