I have this code:
var options = { method: 'POST',
url: 'https://app.nanonets.com/api/v2/ImageCategorization/LabelUrls/',
headers:
{ 'cache-control': 'no-cache',
'Authorization' : 'Basic ' + Buffer.from('MYAPIKEY' + ':').toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded' },
form:
{ urls: message.attachments.first().url,
modelId: '353cea12-4dcc-47ee-b139-dd345157b17d' } };
request(options, function (error, response,body) {
if (error) throw new Error(error);
console.log(body)
});
An example of what the console.log()
shows is:
{"message":"Success","result":[{"message":"Success","prediction":[{"label":"sfw","probability":0.8503612},{"label":"nsfw","probability":0.14963877}],"file":"https://cdn.discordapp.com/attachments/746884075855282249/757723667051577434/B99.png"}]}
But this tells me that it āCannot read property ā0ā of undefinedā:
if(body.result[0].prediction[0].probability < body.result[0].prediction[1].probability){
message.remove()
message.channel.send("Please don't send NSFW images!")
}
(Itās just under the console.log()
)
I tested with jsonquerytool.com and itās right, but it gives me an error.
Anyone know how to fix this?
Any answers appreciated in advance
Eddie
1 Like
I tried this:
var a = {
"message": "Success",
"result": [{
"message": "Success",
"prediction": [{
"label": "sfw",
"probability": 0.8503612
}, {
"label": "nsfw",
"probability": 0.14963877
}],
"file": "https://cdn.discordapp.com/attachments/746884075855282249/757723667051577434/B99.png"
}]
}
console.log(a["result"][0]["prediction"][0]["probability"]) //sfw probability, 0.8503612
Is there any way to JSONify the response body so the keys arenāt strings? Having all these brackets is kind of a painā¦
What you need to figure out is the structure of the response body, which parts are a javascript object and which parts are a JSON string, which look like a javascript object when showing in the log.
For example, if the entire body is a string, you can do
bodyObj = JSON.parse(body)
bodyObj.result[0].prediction[0].probability
If body is an object and body.result is a string, you can do
resultObj = JSON.parse(body.result)
resultObj[0].prediction[0].probability
2 Likes
@mishavee Make sure that JSON.parse works - it only seems to parse strings like
"{key: "val"...}"
and doesnāt parse object Objects.
Yes thatās the point of parse(), to convert a string to an object. If its already an object thereās no need to parse it.
The example you have is misleading, the constant is called ājsonā but its value is an object.
1 Like
Lol, yeah, I just edited the editor on JSON.parse() docs.
Too bad thereās nothing that converts string object keysā¦
Like:
{
"key":value,
"key2": value,
}
Into
{
key: value,
key2: value
}
I assume you want the result to be evaluated as javascript? In which case they would work the same.
Otherwise, what use would it be for?