0

I am very new to Node.JS, can anyone help in below issue.

I am calling REST API and it is returning response body wiht JSON object. But i am not able to parse it properly.

I tried body.destination_addresses[0] to retrieve value but doesn't work.

Here is my code sample

 var parsedjson=JSON.parse(body);
 body.destination_addresses[0];

with parsing I am able to retrieve value of body.destination_addresses[0] but failed to retrieve "parsedjson.rows.elements[1].distance.text" value.

How can I retrieve distance value from JSON.

sample json

body:
{
   "destination_addresses" : [
      "458-500 St Johns Pl, Brooklyn, NY 11238, USA",
      "395 4th Ave, Brooklyn, NY 11215, USA"
      ],
   "origin_addresses" : [ "127 Tech Pl, Brooklyn, NY 11201, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "2.3 mi",
                  "value" : 3624
               },
               "duration" : {
                  "text" : "15 mins",
                  "value" : 899
               },
               "status" : "OK"
            }
  ]
      }
   ],
   "status" : "OK"
}
0

1 Answer 1

1

Your elements array has only one item so you can't get at index 1

As per your sample try this code

body.rows[0].elements[0].distance.text

You need to clear your basic JavaScript and how to use array

Sign up to request clarification or add additional context in comments.

3 Comments

hi,thanks for the response. Still no luck i tried body.rows[i].elements[i].distance.text; (here value of i = 0). error msg: "TypeError: Cannot read property 'elements' of undefined"" .Do you have any idea. [FYI, in my response i have more than 10 values in elements array thats why mentioned elements[1] in my question].
That should work in your case, you are doing something wrong cross check your code, you can post your all response to help
yeah you are corrct its working, i made mistake in increment "i" value and referring that in rows. thanks again..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.