Answer the question
In order to leave comments, you need to log in
How to write new node js object to json file?
I have a .json file with the following content:
[
{
"name": "AUTO",
"price": 20,
"discount": 90,
"img": "https://i.imgur.com/36GYPaK.png",
"maxLPrizes": 4,
}
]
Answer the question
In order to leave comments, you need to log in
const fs = require('fs');
let rawdata = fs.readFileSync('my.json'); // Читаем файл. Название файла поменять на свое
let parseddata= JSON.parse(rawdata); // парсим и получаем JS объект из строки
// Здесь совершаем операции с объектом JS
Например, добавляем объект в массив
parseddata.push({
"name": "AUTO1",
"price": 30,
"discount": 100,
"img": "https://i.imgur.com/36GYPaK1.png",
"maxLPrizes": 5,
});
// Превращаем обратно в строку
let data = JSON.stringify(parseddata);
// Пишем в файл
fs.writeFileSync('my.json', data);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question