JSON query not working - 'Cannot read property '0' of undefined'

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 :slight_smile:
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ā€¦

Thanks for the speedy response :+1: :running_man:
Will try this out tomorrow. I assume the tool I used did what you suggested and somehow JSONified what I gave :slight_smile:

1 Like

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ā€¦

Can you elaborate?

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?