I am trying to use ROBLOX's API to make a ;rs
command but it isn't going so well.
Using request-promise I tried searching and it brought me this error:
SyntaxError: Unexpected token o in JSON at position 1
I have reviewed questions on here before and answered some. If this helps, I am using discord.js-commando for my command handler.
Here is the part the error is coming from:
let editMsg = await msgObject.reply(
":triumph: Finding ROBLOX Account, give me a second!"
);
let rs = await request({
uri: `https://users.roblox.com/v1/users/search?keyword=${idk}&limit=10`,
simple: false,
json: true
});
if (rs.userFacingMessage == "Something went wrong"){
if(rs.code == 5){
editMsg.edit("Sorry 😣, We couldn't process your search! The username you provided has been filtered!");
}
if(rs.code == 6){
editMsg.edit("Sorry 😣, We couldn't process your search! The username you provided is too short!");
}
}else {
let user = JSON.parse(rs)
msgObject.reply(user)
}
Here is a PasteBin link if you need to see the whole run()
method.
request-promise
with the option json: true
automatically parses the JSON string in the response. It means your variable rs
is already an object, not a JSON string.
The JSON.parse()
method parses a JSON string, so when you try to parse an object, Node.js converts it to a string first ([object Object]
). The first character is [
which is valid JSON, but the second one (the letter o
) is not, so you receive a SyntaxError: Unexpected token o in JSON at position 1
.
Try it out below:
const rs = {
previousPageCursor: null
}
try {
console.log(JSON.parse(rs))
} catch (error) {
console.log(error.message)
}
The API endpoint at https://users.roblox.com/v1/users/search?keyword=${idk}&limit=10
returns an object, so you can't simply send it as-is in a reply. You can use JSON.stringify()
to create a string from that object, or you can get an array of users from rs.data
.
If you want to return a single user, you can either grab the first item (rs.data[0]
) from that array, or use the find()
method to find one that matches your keyword:
} else {
const user = rs.data[0]
msgObject.reply(`\`\`\`${JSON.stringify(user, null, 2)}\`\`\``)
}
} else {
const user = rs.data.find((u) => u.name === idk)
msgObject.reply(`\`\`\`${JSON.stringify(user, null, 2)}\`\`\``)
}
PS: Next time when you don't want to be rude, don't write "Not trying to be rude but I want an answer [...]"