The goal of this node.js code is to be able to read, add and delete JSON objects. My JSON code looks like this:
{
"first": [
{
"id": 1112313,
"price": 11
},
{
"id": 11123122413,
"price": 112
}
],
"second": [
{
"id": 4121312,
"price": 55
}
],
"third": [
{
"id": 87845,
"price": 444
}
]
}
The reading part I figured out, but the deleting and adding new objects part doesn't work for me. I only get [Object Object] written in my JSON file. So far my code looks like this:
//Reading JSON file
var fs = require('fs');
var object = JSON.parse(fs.readFileSync('./jsonFile.JSON', 'utf8'));
console.log(object.first[0].price);
//Deleting
delete object.first[0].price
//Adding a new object
object.first[] = {"id":11245, "price": 123};
//Writing results to JSON file
fs.writeFileSync('jsonFile.json', object);
Any ideas how to make it work?
fs.writeFileSync('jsonFile.json', JSON.stringify( object, null, 2 ) );