无法从磁盘上的 json 文件中删除数据

Unable to remove data from json file on disk

我无法找到在使用后删除整行 JSON 数据(行)的方法。 出于某种原因 delete 没有工作,或者说没有做任何事情。

.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":""}
]

代码

//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];

这里的目标是 select 随机代码,这已经完成,但我需要将其从 .JSON 文件中删除,这样它就不会重复。我尝试了几件事,但没有用,delete.randomcode 等...该行从未从 .JSON 文件中删除。

使用 Array.prototype.splice(index, deleteCount) 代替 delete
delete,在数组上,将只 null 键,而不删除它。

使用 JSON.stringify(mycodes) 将修改后的数据保存回同一个文件。

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');

如果您的数组中已经有该对象,并且由于对象是通过引用传递的(就像内存中的指针),请使用 Array.prototype.indexOf(someObject),例如:

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');

您需要在使用 JSON.stringify().

后将数据写回您的 JSON 文件以保留您的数据。

当你这样做的时候,你可以将你的代码移动到函数中,这将使它更容易阅读和使用。

您可能还想阅读有关使用 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);