[英]How to Delete an object from a JSON file in Javascript
So I am trying to delete an Object from a json file in JavaScript and it is proving to be harder than once thought.所以我试图从 JavaScript 中的 json 文件中删除 Object ,事实证明它比以前想象的要难。
This is an example of my JSON file:这是我的 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 } }
And here is an example of what I have so far:这是我到目前为止的一个例子:
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") }); }
So I am wondering if there is a way to check if the property of "OnBlock" is false and if so there a way to delete the entire player from the json.所以我想知道是否有办法检查“OnBlock”的属性是否为假,如果是的话,是否有办法从 json 中删除整个播放器。
the way to delete a key (and his value) of a json is delete json[key]
try with delete client.block[player]
删除 json 的键(及其值)的方法是
delete json[key]
try with delete client.block[player]
You can use a simple if
condition to check whether the onBlock
is false and then use delete
operator to delete a specific JSON Key.您可以使用简单的
if
条件检查onBlock
是否为 false,然后使用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")
});
}
}
You're starting with JSON, so there's no need to fiddle about splitting strings and trying to parse the results.您从 JSON 开始,因此无需担心拆分字符串并尝试解析结果。 Simply use
JSON.parse()
, and work with the resulting object:只需使用
JSON.parse()
,然后使用生成的 object:
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 if you have more then one JSON file which you're going to be reading and writing to, you might as well make a model for it. IMO,如果您要读取和写入的文件不止一个 JSON 文件,您不妨为它制作一个 model。
You could make an index.js
file in ./jsons
, with the following contents:您可以在
./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);
}
}
Then wherever you use ./jsons
you could treat it like a CRUD and it would read/write to the file seamlessly instead of having a bunch of fs.writeFile
's everywhere:然后,无论您在哪里使用
./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);
Your code would look like:您的代码如下所示:
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');
}
}
If you want something more robust, you could use lib like conf .如果你想要更健壮的东西,你可以使用 lib 像conf 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.