Geir
Geir

Reputation: 95

Editing JSON files in NodeJS and DiscordJS

Right, so I am trying to wrap my head around editing (appending data) to a JSON file. The file (users.json) looks like this:

{
  "users": {
    "id": "0123456789",
    "name": "GeirAndersen"
  }
}

Now I want to add users to this file, and retain the formatting, which is where I can't seem to get going. I have spent numerous hours now trying, reading, trying again... But no matter what, I can't get the result I want.

In my .js file, I get the data from the json file like this:

const fs = require('fs').promises;

let data = await fs.readFile('./test.json', 'utf-8');
let users = JSON.parse(data);

console.log(JSON.stringify(users.users, null, 2));

This console log shows the contents like it should:

{
  "id": "0123456789",
  "name": "GeirAndersen"
}

Just to test, I have defined a new user directly in the code, like this:

let newUser = {
  "id": '852852852',
  "name": 'GeirTrippleAlt'
};
console.log(JSON.stringify(newUser, null, 2));

This console log also shows the data like this:

{
  "id": "852852852",
  "name": "GeirTrippleAlt"
}

All nice and good this far, BUT now I want to join this last one to users.users and I just can't figure out how to do this correctly. I have tried so many version and iterations, I can't remember them all. Last tried:

users.users += newUser;
users.users = JSON.parse(JSON.stringify(users.users, null, 2));

console.log(JSON.parse(JSON.stringify(users.users, null, 2)));
console.log(users.users);

Both those console logs the same thing:

[object Object][object Object]

What I want to achieve is: I want to end up with:

{
  "users": {
    "id": "0123456789",
    "name": "GeirAndersen"
  },
  {
    "id": "852852852",
    "name": "GeirTrippleAlt"
  }
}

When I get this far, I am going to write back to the .json file, but that part isn't an issue.

Upvotes: 0

Views: 730

Answers (1)

Steve -Cutter- Blades
Steve -Cutter- Blades

Reputation: 5432

That's not really a valid data structure, as you're trying to add another object to an object without giving that value a key.

I think what you're really looking for is for 'users' to be an array of users.

{
  "users": [
    {
      "id": "0123456789",
      "name": "GeirAndersen"
    },
    {
      "id": "852852852",
      "name": "GeirTrippleAlt"
    }
  ]
}

You can easily create an array in JS and the push() new items into your array. You JSON.stringify() that with no issue.

const myValue = {
  users: []
};

const newUser = {
  'id': '0123456789',
  'name': "GeirAndersen'
};

myValue.users.push(newUser);

const strigified = JSON.stringify(myValue);

Upvotes: 1

Related Questions