I've the following users.json
file:
[
{
"name": "John",
"surname": "A",
"number": 3
}
]
I would like to add a new element to this file, for example:
[
{
"name": "John",
"surname": "A",
"number": 3
},
{
"name": "Mike",
"surname": "B",
"number": 7
}
]
I'm new to NodeJS / TypeScript, so I can't do it. I thought of a solution similar to this:
import json from "./users.json"
export type User = {
name: string,
surname: string,
number: number
};
export function add_user(new_user: User) {
let number_of_elements = Object.keys(json).length;
json[number_of_elements] = new_user;
}
I know this is wrong, but I can't understand how to do it. Can you help me? Thank you everybody.
CodePudding user response:
What you want to do here is simply add an item to an array, considering that User is the type of your array.
You can have the array from your file by using the stringify and parse methods.
So what you can simply do is to declare an array of type User, and add the elements to the array with the push methodn and then reformat it as JSON object :
export type User =
{
name: string,
surname: string,
number: number
};
let userArray Array<User> = JSON.parse(JSON.stringify(json))
export function add_user(new_user: User) {
userArray.push(new_user);
}
//use the fonction like this :
add_user({
"name": "John",
"surname": "A",
"number": 3
});
add_user({
"name": "Mike",
"surname": "B",
"number": 7
});
If your file is stored locally you will then have to rewrite it, using fs.writeFile :
const fs = require('fs');
try
{
fs.writeFile(pathToYourFile, JSON.stringify(JSON.parse(userArray), function(err: any){
if(err) return console.log(err);
});
}
catch(err)
{
console.error(err);
}