【问题标题】:How to Delete an object from a JSON file in Javascript如何在 Javascript 中从 JSON 文件中删除对象
【发布时间】:2021-03-24 17:19:06
【问题描述】:

所以我试图从 JavaScript 中的 json 文件中删除一个对象,事实证明它比以前想象的要难。

这是我的 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 json discord.js


    【解决方案1】:

    IMO 如果您要读取和写入的 JSON 文件不止一个,您不妨为它制作一个模型。

    你可以在./jsons中创建一个index.js文件,内容如下:

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

    如果你想要更健壮的东西,你可以使用像 conf 这样的 lib。

    【讨论】:

      【解决方案2】:

      您从 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
      

      【讨论】:

        【解决方案3】:

        您可以使用简单的if 条件来检查onBlock 是否为false,然后使用delete 运算符删除特定的JSON Key。

        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")
                });
                }
                
            }
        

        【讨论】:

          【解决方案4】:

          删除json的键(及其值)的方法是delete json[key] 试试delete client.block[player]

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-03-25
            • 1970-01-01
            • 2020-10-15
            • 1970-01-01
            • 2012-02-29
            • 1970-01-01
            • 2011-01-16
            • 1970-01-01
            相关资源
            最近更新 更多