Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to remove data from json file

I’m unable to find a way to remove whole line of JSON data(line) after it’s used.
For some reason delete is not working or rather said not doing anything.

.JSON

[
{"id":"1","code":"super-S","expires_in":"","gives_currencies":"1.5","gives_items":"","number_of_attempts":"1","attempts_used":""},
{"id":"2","code":"wow!","expires_in":"","gives_currencies":"3","gives_items":"","number_of_attempts":"1","attempts_used":""},
{"id":"3","code":"slashme","expires_in":"","gives_currencies":"4","gives_items":"","number_of_attempts":"1","attempts_used":""},
{"id":"4","code":"randombla","expires_in":"","gives_currencies":"5","gives_items":"","number_of_attempts":"1","attempts_used":""}
]

code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//fs configuration
const fs = require('fs');
let rawdata = fs.readFileSync('test.json');
let mycodes = JSON.parse(rawdata);

//something above
const randomcode = mycodes[Math.floor(Math.random() * mycodes.length)];
console.log('Your code is:', randomcode['code']); //logs me a random code value
delete mycodes[randomcode];

The goal here is to select random code, which is done but then I need to remove it from .JSON file so it won’t repeat. I tried several things but it’s not working, delete.randomcode etc… the line never removed from the .JSON file.

>Solution :

Don’t use delete on an Array, since it will just null your key value (without removing that key).
Use Array.prototype.splice(index, deleteCount)

Than, make sure to save back your modified mycodes using JSON.stringify(mycodes) to that same file.

const fs = require('fs');

const mycodes = JSON.parse(fs.readFileSync('./test.json'));
const randomIndex = Math.floor(Math.random() * mycodes.length)
const randomcode = mycodes[randomIndex];

console.log('Your code is:', randomcode.code); // Log a random code value
mycodes.splice(randomIndex, 1); // Remove one key at randomIndex

// Write back to file
fs.writeFileSync('test.json', JSON.stringify(mycodes, 0, 4), 'utf8');

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading