如何检查.json文件中的用户ID是否存在
continue
I'm trying to find ID from the .JSON file so I can do a match if statement, current problem is that users are saved in .JSON each time, not just once. So I was looking for a way to find User's ID in the .JSON and then compare it with the statement, but I'm unable to get just the ID from the .JSON(check if the ID exists in that file).
empty .JSON
{
"users": [
]
}
.JSON with collected users
{
"users": [
{
"id": "1",
"username": "USER1"
},
{
"id": "1",
"username": "USER1"
},
{
"id": "2",
"username": "USER2"
},
{
"id": "2",
"username": "USER2"
}
]
}
EDIT
Code:
let rawuserstats = fs.readFileSync(__dirname + '/users.json', 'utf8');
const userstats = JSON.parse(rawuserstats);
console.log(userstats)
//something above...
const foundUser = userstats.users.find(m => m.id === message.author.id)
console.log('Found user:', foundUser)
if (foundUser !== message.author.id) { //try to match user ID with the .JSON(not working)
//Put user's data to the .JSON
userstats.users.push({id: message.author.id, username: message.author.username});
fs.writeFileSync(__dirname + '/users.json', JSON.stringify(userstats, 0, 4), 'utf8');
}
//something else...
console.log('Found user:', foundUser)
returns undefined
if .JSON is empty, then after users are in the .JSON { id: '1', username: 'USER1' }
, even if I used USER2 for the command instead. Didn't figure out how to get just the ID so I can compare it...
I tried const foundUser = userstats.users.find(id => id === message.author.id)
but this will always return undefined
while using console.log('Found user:', foundUser)
. I'm a bit confused about it.
EDIT
I made some progress const foundUser = userstats.users.find(m => m.id === message.author.id)
this will return undefined when the user is not inside of the .JSON, and returns this response when user is in the .JSON { id: '1', username: 'USER1' }
or { id: '2', username: 'USER2' }
from our example. I just need pick the ID value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了解决方案,所以将其发布在这里。
由于 findUser 返回未定义,我能够使用这种语句并且它有效,用户不再在 .JSON 文件中重复。
但我仍然想知道,如何才能获得 ID 响应(在本例中为
1
)而不是{ id: '1', username: 'USER1' }
,可以通过.find
实现吗?I found a solution, so posting it right here.
As foundUser returns undefined, I was able to use this kind of statement and it works, users are not duplicating in .JSON file anymore.
But I would still like to know, how I can get just the ID response (in this case
1
) instead of{ id: '1', username: 'USER1' }
, is that possible via.find
?