I am new to using JSON files in my code, and I'm trying to set up a system where there are two values:
"User" and "Points"
What I intend the JSON file to be approximately formatted as is:
{
Aurora: 5,
Jack: 2,
Ariel: 10,
}
Honestly, any format will do. If there's already an "Aurora", it'll either add or remove points to the value. If there's a new user that inputs a command, lets say "John", it'll create a new JSON line (or array):
{
Aurora: 5,
Jack: 2,
Ariel: 10,
John: 0,
}
So on so forth, with each new user adding a new line to the JSON file with the respective points. How can I achieve this?
CodePudding user response:
Here is an example of how you can achieve this but as others mentioned, you are writing in js syntax not json syntax. I highly suggest you to read up on the basics of javascript, node and json. Google has the answer.
First, you will need to create a users.json file in the same directory as your Node.js script, and populate it with the initial values you want to use, like this:
{
"Aurora": 5,
"Jack": 2,
"Ariel": 10
}
Then, in your Node.js script, you can read the users.json file using the fs module and parse it using the json module. You can then add or update the values for each user, and write the updated data back to the users.json file. Here is an example of how you can do this:
const fs = require('fs');
const json = require('json');
// Read the users.json file
const data = fs.readFileSync('users.json');
// Parse the JSON data
const users = json.parse(data);
// Add or update the points for each user
users.Aurora = 5;
users.Jack -= 1;
users.Ariel = 10;
users.John = 0;
// Write the updated data back to the users.json file
fs.writeFileSync('users.json', json.stringify(users));
This code will update the users.json file to have the following content:
{
"Aurora": 10,
"Jack": 1,
"Ariel": 20,
"John": 0
}
You can then continue to update the users.json file as needed in your code.
CodePudding user response:
There are a couple of different approaches to this. A simple approach is to hold the data as a constant and manipulate it on every update. Using a function to do this is probably the most straight-forward approach as the function can then be called whenever new data has to be added to the data object.
const data = {
Aurora: 5,
Jack: 2,
Ariel: 10,
};
function addToData(name, value) {
data[name] = data[name] ? data[name] value : value;
}
addToData('John', 3);
addToData('Aurora', 2);
console.log(data);
Another approach is to use a pure function that doesn't manipulate the original value and returns a new data object. This reduces the chance of there being unwanted side-effects, but a little more copmlex.
let dataObj = {
Aurora: 5,
Jack: 2,
Ariel: 10,
};
function addToData(data, name, value) {
const newData = {
...data
};
newData[name] = data[name] ? data[name] value : value;
return newData;
}
dataObj = addToData(dataObj, 'John', 3);
dataObj = addToData(dataObj, 'Aurora', 2);
console.log(dataObj);