Как удалить объект из файла JSON в Javascript

Итак, я пытаюсь удалить объект из файла json в JavaScript, и это оказывается сложнее, чем предполагалось.

Это пример моего файла JSON:

{
    "tom cruise": {
        "player": "tom cruise",
        "team": "buf",
        "position": "qb",
        "overall": "82",
        "OnBlock": true
    },
    "tim tebow": {
        "player": "tim tebow",
        "team": "buf",
        "position": "qb",
        "overall": "82",
        "OnBlock": false
    }
}

И вот пример того, что у меня есть до сих пор:

client.block = require ("./jsons/tradeblock.json")

if (message.content.startsWith('tb!remove')) {
        player = message.content.toLowerCase().slice(10)
        array = player.toLowerCase().split(" - ")
        team = array[0]
        position = array[1]
        player = array[2]
        overall = array[3]
        client.block [player] = {
            player: player,
            team: team,
            position: position,
            overall: overall,
            OnBlock: false
        }
        fs.writeFile ("./jsons/tradeblock.json", JSON.stringify (client.block, null, 4), err => {
            if (err) throw err;
            message.channel.send("Removing from block")
        });
    }

Поэтому мне интересно, есть ли способ проверить, является ли свойство «OnBlock» ложным, и если да, то есть ли способ удалить весь проигрыватель из json.

🤔 А знаете ли вы, что...
JavaScript поддерживает модульную структуру, что способствует организации кода на больших проектах.


937
4

Ответы:

способ удалить ключ (и его значение) json — это delete json[key] попробуй с delete client.block[player]


Решено

Вы можете использовать простое условие if, чтобы проверить, является ли onBlock ложным, а затем использовать оператор delete для удаления определенного ключа JSON.

client.block = require ("./jsons/tradeblock.json")

if (message.content.startsWith('tb!remove')) {
        player = message.content.toLowerCase().slice(10)
        array = player.toLowerCase().split(" - ")
        team = array[0]
        position = array[1]
        player = array[2]
        overall = array[3]
        client.block [player] = {
            player: player,
            team: team,
            position: position,
            overall: overall,
            OnBlock: false
        }
        if (!client.block[player].onBlock){
           delete client.block[player];
           fs.writeFile ("./jsons/tradeblock.json", JSON.stringify (client.block, null, 4), err => {
            if (err) throw err;
            message.channel.send("Removing from block")
        });
        }
        
    }

Вы начинаете с JSON, поэтому вам не нужно возиться с разбиением строк и попыткой проанализировать результаты. Просто используйте JSON.parse() и работайте с полученным объектом:

const srcJSON = '{"tom cruise": {"player": "tom cruise","team": "buf","position": "qb","overall": "82","OnBlock": true},"tim tebow": {"player": "tim tebow","team": "buf","position": "qb","overall": "82","OnBlock": false}}';

let players = JSON.parse(srcJSON);             // Parse JSON into a javascript object

Object.keys(players).forEach(function(key){    // Iterate through the list of player names
    if (!players[key].OnBlock) {               // Check the OnBlock property
        delete players[key]                    // delete unwanted player
    }
});

let output = JSON.stringify(players);          //Convert back to JSON

IMO, если у вас есть более одного файла JSON, который вы собираетесь читать и записывать, вы также можете создать для него модель.

Вы можете создать файл index.js в ./jsons со следующим содержимым:

const jsonFile = new (class {
  constructor() {
    this.fs = require('fs');
  }
  get(filePath) {
    return JSON.parse(
      Buffer.from(this.fs.readFileSync(filePath).toString()).toString('utf-8')
    );
  }
  put(filePath, data) {
    return this.fs.writeFileSync(filePath, JSON.stringify(data, null, 4), {
      encoding: 'utf8'
    });
  }
})();

module.exports = class jsons {
  constructor(file) {
    this.file = './jsons/' + file + '.js';
    this.data = jsonFile.get(file);
  }
  get() {
    return this.data;
  }
  add(key, data) {
    this.data[key] = data;
    jsonFile.put(this.file, this.data);
  }
  remove(key) {
    delete this.data[key];
    jsonFile.put(this.file, this.data);
  }
}

Затем, где бы вы ни использовали ./jsons, вы можете обращаться с ним как с CRUD, и он будет беспрепятственно читать/записывать в файл вместо того, чтобы повсюду иметь кучу fs.writeFile:

const jsons = require('./jsons')

let client = {};

client.block = new jsons('tradeblock');
// client.foo = new jsons('foo');
// client.bar = new jsons('bar');

// get
let all_clients = client.block.get();

// add (will replace if same key)
let player = 'Loz Cherone';
let team = 'foo team';
let position = 'relative';
let overall = 'dungarees'

client.block.add(player, {
  player,
  team,
  position,
  overall,
  OnBlock: true,
});

client.block.remove(player);

Ваш код будет выглядеть так:

const jsons = require('./jsons')

let client = {};
client.block = new jsons('tradeblock');

if (message.content.startsWith('tb!remove')) {
  let player = message.content.toLowerCase().slice(10);
  const array = player.toLowerCase().split(' - ');
  if (array.length >= 3) {
     player = array[2];
     client.block.remove(player);
     message.channel.send('Removing from block');
  } else {
     message.channel.send('Invalid block structure');
  }
}

Если вам нужно что-то более надежное, вы можете использовать lib, например conf.