所以我是js的初学者,在json文件中有一个用户表,我正在制作一个帐户删除功能。我有一个查找设置来查找用户,它工作得很好,但我不知道如何让它从文件中删除用户,任何帮助都将不胜感激!
Json:
{
"users": [
{
"name": "ImBattleDash",
"Id": "780748c5d4504446bbba3114ce48f6e9",
"discordId": "471621420162744342",
"dateAdded": 1548295371
}
]
}
JS:
function findJson() {
fs.readFile('./linkedusers.json', 'utf-8', function (err, data) {
if (err) message.channel.send('Invalid Code.')
var arrayOfObjects = JSON.parse(data)
let findEntry = arrayOfObjects.users.find(entry => entry.discordId == myCode)
let linkEmbed = new Discord.RichEmbed()
.setTitle('Account unlinked!')
.setDescription('Link your account by friending "BattleDash Bot" on Fortnite and then input the code you get messaged by typing "!link <code>"!')
.setColor('#a900ff');
message.channel.send({embed: linkEmbed});
})
}
编辑:不确定是数组还是表我对json 不太了解
您需要使用:
Array#find
以通过某些给定的标准来查找给定的用户Array#indexOf
获取在users
中找到的用户的索引- CCD_ 4从CCD_ 5给出的索引开始丢弃一个元素:
const input = {
"users": [
{
"name": "ImBattleDash",
"Id": "780748c5d4504446bbba3114ce48f6e9",
"discordId": "471621420162744342",
"dateAdded": 1548295371
}
]
}
const removeUser = (criteria, users) =>
users.splice (users.indexOf (users.find (criteria)), 1)
removeUser (
({ Id, discordId }) =>
Id == '780748c5d4504446bbba3114ce48f6e9'
&& discordId == '471621420162744342',
input.users
)
// Output: 0 <-- User has been removed!
console.log(input.users.length)
关于持久化更改,只需要调用JSON.stringify (input)
,然后将内容写入所需的输出文件。请参阅其他问答;A: 在Node.js 中写入文件
在Cat和Matias的大力帮助下,我想出了这个有效的代码!
function findJson() {
fs.readFile('./linkedusers.json', 'utf-8', function (err, data) {
if (err) message.channel.send('Invalid Code.')
var arrayOfObjects = JSON.parse(data)
let findEntry = arrayOfObjects.users.find(entry => entry.discordId == myCode)
const input = arrayOfObjects;
const removeUser = (criteria, users) =>
users.splice (users.indexOf (users.find (criteria)), 1)
removeUser (
({ Id, discordId }) =>
Id == findEntry.Id
&& discordId == findEntry.discordId,
input.users
)
console.log('unlinked')
fs.writeFile('./linkedusers.json', JSON.stringify(arrayOfObjects, null, 4), 'utf-8', function(err) {
if (err) throw err
console.log('Done!')
})
let linkEmbed = new Discord.RichEmbed()
.setTitle('Account unlinked!')
.setDescription('Link your account by friending "BattleDash Bot" on Fortnite and then input the code you get messaged by typing "!link <code>"!')
.setColor('#a900ff');
message.channel.send({embed: linkEmbed});
})
}
这里有一个快速教程:"用户"可以是一个数组(使用[]
)或一个javascript对象(使用{}
),由您选择。除非你使用数据库而不是JSON文件,否则不会有任何实际的表(尽管如果你的JSON表达式像你的例子一样简单,你几乎可以把它想象成一个表。)——实际上,第三种选择是使用JavaScriptMap类型,它就像一个增强的对象,但我不会在这里解决这个问题。
虽然使用数组可以更容易地检索所有用户的数据列表(因为数组更容易迭代),但使用对象可以更轻松地检索单个的数据(因为您可以通过其键直接指定您想要的用户,而无需在整个数组中循环,直到找到您想要的。)我将向您展示一个使用对象的示例。
示例代码中的单个用户就是javascript对象的一个示例。JSON允许您将对象转换为字符串(用于存储、I/O和人类可读性),然后再转换回对象(以便javascript能够理解它)。您分别使用JSON.stringify()和JSON.parse()方法进行这些转换。字符串必须是JSON格式的,否则这将不起作用,您的示例是JSON格式中的几乎。
为了遵守JSON格式,您可以按如下方式构造Users对象。(当然,我们看到的是字符串化版本,因为只有人类无法轻松读取"实际"的javascript对象):
"Users": { // Each individual user is a property of your users object
"780748c5d4504446bbba3114ce48f6e9": // The Id is the key in the "key/value pair"
{ // The individual user object itself is the value in the key/value pair
// Id is duplicated inside user for convenience (not necessarily the best way to do it)
"id": "780748c5d4504446bbba3114ce48f6e9",
"name": "ImBattleDash", // Each property of the user is also a key/value pair
"discordId": "471621420162744342", //Commas separate the properties of an object
"dateAdded": "1548295371" // All property values need double quotes for JSON compatibility
}, // Commas separate the properties (ie the individual users) of the users object
"446bbba3114ce48f6e9780748c5d4504": // This string is the second user's key
{ // This object is the second user's value
"id": "446bbba3114ce48f6e9780748c5d4504",
"name": "Wigwam",
"discordId": "162744342471621420",
"dateAdded": "1548295999"
}
}
从存储中检索字符串后,将其转换为对象并删除用户,如下所示。(为了清晰起见,这被分解为更多的步骤。):
let usersObject = JSON.parse(stringRetrievedFromFile);
let userId = "780748c5d4504446bbba3114ce48f6e9";
let userToModifyOrDelete = usersObject[userId];
delete userToModifyOrDelete;
要更改用户的discordId,您可以执行以下操作:
let discordId = userToModifyOrDelete.discordId; // Not necessary, just shows how to retrieve value
let newDiscordId = "whateverId";
userToModifyOrDelete.discordId = newDiscordId;
您可以将对象转换回字符串,并使用存储在文件中
JSON.stringify(usersObject);
希望这几乎就是您需要了解的关于JSON的全部内容!