Learning to retrieve JSON data from an API using JavaScript

https://i.sstatic.net/OQZvD.pngGreetings! I am currently facing an issue while trying to retrieve JSON data from an API. Whenever I attempt to extract data from the API, everything works smoothly except for when I try to access the distance value, which results in undefined. Any assistance would be greatly appreciated.

Here is the code snippet:

fetch('https://maps.googleapis.com/maps/api/distancematrix/json?units=meter&origins=Gurd%20Shola%201%20Station,%20Addis%20Ababa&destinations=Bole%20Medhane%20Alem%20Church,%20Addis%20Ababa&key=API_KEY')
  .then(response => {
    return response.json()
  })
  .then(data => {
// Work with JSON data here
console.log(data.rows.elements.distance.value)
 })
  .catch(err => {

 })

The retrieved result from the web appears as follows:

{
   "destination_addresses" : [ "Addis Ababa, Ethiopia" ],
   "origin_addresses" : [ "Addis Ababa, Ethiopia" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "6.4 km",
                  "value" : 6386
               },
               "duration" : {
                  "text" : "15 mins",
                  "value" : 901
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Answer №1

Replace

data.rows.elementes.distance.value
with
data.rows[0].elements[0].distance.value
..

Make sure there are no typos here, it should be elements and not elementes..

Remember that both rows and elements are arrays, so to access the distance you should use rows[0].elements[0].distance ..

const data = {
   "destination_addresses" : [ "Addis Ababa, Ethiopia" ],
   "origin_addresses" : [ "Addis Ababa, Ethiopia" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "6.4 km",
                  "value" : 6386
               },
               "duration" : {
                  "text" : "15 mins",
                  "value" : 901
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

console.log(data.rows[0].elements[0].distance);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error 400: The onCreate Trigger function for Cloud functions is experiencing issues with HTTP requests due to errors in the request

I am encountering an issue when attempting to add a trigger for Firestore OnCreate, as the deployment fails with HTTP Error: 400 stating that the request has errors. Essentially, my goal is to write to a new document if a record is created in a different ...

RecyclerView malfunctioning: issue with attaching adapter

I'm having issues with my adapter class. I've been troubleshooting why the adapter isn't attaching to the recycler view, it keeps skipping layout. I'm not familiar with coders experienced in using Recyclers and I'm unsure where I&a ...

Creating AngularJS variables with dependencies on integer values

Hello, I am a brand new developer and I am currently working on creating an expenses calculator. The goal is to have the sum of inputted integers from a table, each with a default value, become the integer value of another variable. However, I seem to be m ...

Generating a JSON array using PHP

Hey there, I'm currently working on creating an array for easier access to some data in my ESP32 project. The issue I'm facing is with the Json 6 library - specifically, I can't seem to access the contents of the array as intended. For examp ...

The initial JSON value stored in the Laravel Database

I am currently handling form data to be saved into the database, but facing an issue where the first record is being duplicated multiple times during the saving process. return response()->json($request->all()); JSON ... I am encountering difficult ...

Deciphering the method to retain added text

Imagine you have this code snippet: $('.button').click(function() { $('body').append("<p>Random Text</p>"); }); Whenever the .button is clicked, text is added to the body. How can we make sure that this text is saved a ...

Querying for the presence of an ObjectId in an array in Mongoose

I'm developing a Node.js project that involves two models: User and Project. Below is the Schema for the Project model: const ProjectSchema = new mongoose.Schema({ name: { type: String, maxlength: 50, required: true, } ...

Having trouble with sending volley requests to the server - need some assistance, please

I am having trouble converting a List of objects into a JSON array and then passing it to the server for submission. I have attempted this multiple times without success. I believe the issue lies in the part where I convert the List of objects into a JSON ...

Implement styling based on user input - Transmit form data via PHP to designated email address

My form allows people to provide their details and share their current timetable. I then group them based on suitable times The PHP form currently prints either 'work' or 'free' into a table cell, based on user selection in the form, a ...

Is there a way to retrieve a comprehensive list of all the potential routes in my nuxt.js project?

Is there a way to retrieve a list of all the potential routes in my nuxt.js project? (this would include all URLs) ...

Error: An unexpected character was found in the Gulpfile.js

Having an issue in my Gulpfile.js: gulp.task('webpack', gulp.series(async () => { const option = yargs.argv.release ? "-p" : "-d"; execSync(`node_modules/webpack-cli/bin/cli.js ${option}`, { stdio: [null, process.stdout, proce ...

Execute personalized instructions as run configurations in Visual Studio Code

I'm currently exploring the process of creating a custom run configuration in Visual Studio Code, and I have yet to come across any documentation that addresses my specific scenario. My goal is to establish a Run Configuration that can execute arbitr ...

Sending data to server with Backbone (using save() function and php script)

Wondering if you can assist me with an issue I'm facing. I am trying to utilize Backbone's save() method and send data to a php file. However, I encountered a problem right at the beginning. When I execute the following in the browser's co ...

Checkbox search column in jQuery DataTables

I have implemented jQuery DataTables Individual Column Searching on a table where one of the columns contains checkboxes. HTML Structure <table id="NewTable" class="table table-bordered table-striped"> <thead> <tr> ...

JavaScript application throwing error: "require is not defined"

Currently, I am working on storing an array in a .json file using NodeJS. However, when trying to execute the code below, I encountered an error message saying require is not defined. Can someone provide some guidance on how to resolve this issue? let ans ...

What is the best way to separate and break up this string in Golang?

I just got this {"text":"hello, world!"} response on my API endpoint and I'm working in Go. Can anyone advise how to properly access it? query = hello, world! ...

The function .click() fails to execute upon page load, yet it functions successfully when utilized in the console

This is the code I am using: <script> document.getElementById("test").click(); </script> When I try to trigger the click(); function on page load, it doesn't work. However, when I execute it in the console on Firefox, it works ...

Combining duplicate keys in JSON aggregation using MySQL's many-to-many relationship

I'm facing a challenge with returning a JSON representation of a many-many join. My initial plan was to encode the columns returned in the following unique JSON format { "dog": [ "duke" ], "location": [ &quo ...

A step-by-step guide to implementing lodash once in Vuejs

I am faced with the following input scenario. <input type="text" maxlength="50" v-on:input="query = $event.target.value" v-on:keyup.enter="once(search)" /> Additionally, there are ...

Tips for integrating jwt token into axios request

I am facing an issue with my backend endpoint. I can successfully retrieve a list of customers using jwt token on Postman, but when I try to fetch the list from a React app using axios get request, it fails. After reading through this question, I implemen ...