1

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?

1
  • 1
    fs.writeFileSync('jsonFile.json', JSON.stringify( object, null, 2 ) ); Commented Apr 30, 2019 at 15:14

1 Answer 1

1

You'll probably want something 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', JSON.stringify(object));

The JSON.stringify is important because you'll get the dreaded [object Object] otherwise.

Also note how object.first has been set to a new array here.

Sign up to request clarification or add additional context in comments.

6 Comments

Hmm yeah that works, one thing though, the delete part seems to wipe the entire first object. Any way to just wipe one and leave the other intact?
Yep, like this: delete object.first[0]["price"] - note how you use the square bracket notation here. You can also do the reverse when adding: object.first[0]["price"] = 123
Well, sort of the reverse anyway.
Oh and I'm left with {"first":[null,{"id":11123122413,"price":112},{"i... the nasty null. Easy way to get rid of it?
Are you definitely using delete object.first[0]["price"] and not just delete object.first[0]?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.