简体   繁体   中英

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. 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:

{
  "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:

{
  "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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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