Search code examples
javascriptarraysjsongoogle-cloud-vision

inner json array cannot be accessed in javascript, but can console log the complete json


console.log(e.responseText); testNature(e.responseText.responses[0]);

I cannot use the inner array of a JSON response it says:-

'Uncaught TypeError: Cannot read property '0' of undefined'

when I console log the e.responseText I get:-

 {
  "responses": [
    {
      "labelAnnotations": [
        {
          "mid": "/m/06mb1",
          "description": "rain",
          "score": 0.930509,
          "topicality": 0.930509
        },
        {
          "mid": "/m/0838f",
          "description": "water",
          "score": 0.91255623,
          "topicality": 0.91255623
        },
        {
          "mid": "/m/01ctsf",
          "description": "atmosphere",
          "score": 0.86684966,
          "topicality": 0.86684966
        },
        {
          "mid": "/m/04k84",
          "description": "light",
          "score": 0.8194458,
          "topicality": 0.8194458
        },
        {
          "mid": "/m/01bqvp",
          "description": "sky",
          "score": 0.7569251,
          "topicality": 0.7569251
        }
      ]
    }
  ]
}

but cannot use the inner array e.responseText.responses[0] to call a function ie testNature(e.responseText.responses[0]) . I got the JSON from google cloud vision API


Solution

  • Short version

    Convert the string to object using:

    responseText = JSON.parse(responseText);
    

    Explanation

    e.responseText.responses[0]
    

    gives error - Cannot read property 0 of undefined

    Means e.responseText.responses is undefined.

    Means e.responseText don't have a defined property responses

    Means e.responseText is not the object we are looking for.

    In this context, It Means type of e.responseText is likely string

    To confirm, log the data type of the same using:

    console.log(typeof(e.responseText))
    

    if this gives output string, convert the same to an object using JSON.parse