Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

537
Views
Unable to remove data from json file on disk

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

//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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Use Array.prototype.splice(index, deleteCount) instead of delete.
delete, on an Array, will just null the key, without removing it.

Save back your modified data 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 randomObject = mycodes[randomIndex];

console.log('Your code is:', randomObject.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');

If you already have that Object out of your Array, and since Objects are passed by reference (like pointer in memory), make use of the Array.prototype.indexOf(someObject) like:

const fs = require('fs');

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

// later in your code....
const objIndex = mycodes.indexOf(randomObject); // Get Object index in Array
mycodes.splice(objIndex, 1); // Remove it from array at that index

// Write back to file
fs.writeFileSync('test.json', JSON.stringify(mycodes, 0, 4), 'utf8');
over 4 years ago · Santiago Trujillo Report

0

You need to persist your data by writing it back to your JSON file after using JSON.stringify().

While you're at it, you can move your code into functions, which will make it easier to read and work with.

You might also want to read about editing arrays using Array.prototype.splice().

The delete operator is for deleting properties from objects. While you can use it to delete elements from an array, it will leave the index empty rather than closing the gap in the array after deletion.

const fs = require('fs');

// get a random element from any array
function getRandomElement (array) {
  const randomElement = array[Math.floor(Math.random() * array.length)];
  return randomElement;
}

function deleteElementFromArray (array, element) {
  const index = array.indexOf(element);
  if (index < 0) return false;
  array.splice(index, 1);
  return true;
}

// move the reading work inside a function
function readJson (filePath) {
  const json = fs.readFileSync(filePath, {encoding: 'utf8'});
  const data = JSON.parse(json);
  return data;
}

// move the reading work inside a function
function writeJson (filePath, data) {
  const json = JSON.stringify(data);
  fs.writeFileSync(filePath, json);
}


const jsonFilePath = 'test.json';

const mycodes = readJson(jsonFilePath);
const randomcode = getRandomElement(mycodes);
console.log('Your code is:', randomcode['code']);

deleteElementFromArray(mycodes, randomcode);
writeJson(jsonFilePath, mycodes);

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!