Establishing a connection to a JSON API to retrieve and process

I am trying to extract all instances of names from this page: .

For guidance, I have been using this tutorial as a reference: . However, when I run the code provided, it doesn't return anything. What could be going wrong?

var request = new XMLHttpRequest();

request.open('GET', 'api.openparliament.ca/politicians/?format=json', true);
request.onload = function () {

  // Accessing JSON data
  var data = JSON.parse(this.response);
  if (request.status >= 200 && request.status < 400) {
    data.forEach(politician => {
      console.log(politician.name);
    });
  } else {
    console.log('Error');
  }
}

request.send();

Answer №1

Greetings Sean and welcome to StackOverflow.

It appears that there are a few issues in your code that need to be addressed.

  • Make sure to include http:// in the URL within this line of code:
    request.open('GET', 'http://api.openparliament.ca/politicians/?format=json', true);
    .
  • You should wait for the XMLHttpRequest.readyState to reach DONE. You can check the readyState property like this:

if (request.readyState === 4) {
    // Your code goes here...
}

  • Ensure that the XMLHttpRequest returns a status code of 200. You can do this by checking:

if (request.status === 200) {
    // Your code goes here...
}

Following that, you can use the following code:

var data = JSON.parse(this.response);

Here, data is an object with two properties: objects (an array of objects) and pagination (an object).

You can then iterate through the array of objects like so:

data.objects.forEach(politician => {
  console.log(politician.name);
});

Feel free to refer to the complete demo below for more clarity:

(function() {

  var request = new XMLHttpRequest();
  request.open('GET', 'http://api.openparliament.ca/politicians/?format=json', true);
  request.onreadystatechange = function() {
    if (request.readyState === 4) {
      if (request.status === 200) {
        var data = JSON.parse(this.response);
        data.objects.forEach(politician => {
          console.log(politician.name);
        });
      } else {
        console.log('error');
      }
    }
  }

  request.send();
}());

I hope this information proves helpful.

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

React - Issue with Input event handling when utilizing both onChange and onKeyDown functions

I was attempting to create a feature similar to a multi-select, where users could either choose a value from a list or enter a new value. The selected value should be added to an array when the user presses the enter key. To monitor changes in the input ...

resolved after a new promise returned nothing (console.log will output undefined)

Here is my Promise Function that iterates through each blob in Azure BlobStorage and reads each blob. The console.log(download) displays the values as JSON. However, when trying to close the new Promise function, I want the resolve function to return the ...

The integration of a side panel with a chrome extension is experiencing issues

I am working on a chrome extension with the following functionalities - Extract URL path from a specific webpage. (The webpage's URL remains constant) Open this URL in a new tab. It can be either http:// or https://. Embed an iframe containing a sim ...

how can I transfer model values to a dashboard in Rails 5?

I have developed an app that includes an adminlte dashboard. The dashboard is populated with various values obtained by a jQuery file. I am trying to pass module values to the dashboard. For example, the number of users shown in the dashboard should be fet ...

`I'm experiencing difficulty sending JSON data to Typeahead using PHP`

I am having trouble passing an array of data from PHP to typeahead. I have tried various solutions but nothing seems to work. When I display the response on the console, it shows the array of strings but they are not populating in the typeahead field. PHP ...

Leverage videojs-vr within a Vue.js component

I have been experimenting with integrating the videojs-vr package, which I installed through npm, into a Vue.js component. However, I encountered an error: TypeError: videojs is not a function at VueComponent.mounted (VR.vue?d2da:23) at callHook (vue.esm. ...

Is it possible for the binding model of Mat-Checkbox to be optional or null?

Greetings everyone! I am a newcomer to the world of Angular, where I have successfully created a dynamic list of checkboxes. However, I have encountered a challenge when trying to bind selected values from an API to these checkboxes. <div *ngFor="let b ...

Ways To Obtain Trustworthy Dates Using JavaScript

Last week, I encountered an intriguing issue at my job. I needed to obtain a date accurately using JavaScript, but the code I was working with utilized new Date() which resulted in discrepancies due to some customers having incorrect system time settings. ...

What is the best way to personalize the collector for each individual?

Currently, I have a bot that is capable of collecting messages and replying if it detects a specific word. However, I am facing an issue where the bot keeps creating new collectors every time someone types the word tekong. As a result, the bot ends up resp ...

Having issues with deserializing boolean data types from a JSON file in Python

I am working with a json file and facing an issue where the content is not properly decoding the string "false" to False in Python 2.7.6 (not yet tested in Python3). { "qps": 30, "force_push": "false" } Here is the code snippet that is failing to dec ...

Creating a POST request in Rails 3

Is there a way to integrate web services in Rails 3 by sending POST parameters to an external URL? Typically, I utilize a command line method like the one below for posting: curl -X POST -u "v10REVkw:XuCqIhyCw" \ -H "Content-Type: application/json" & ...

Error encountered while attempting to save a Mongoose post on Heroku, although it is successful

My aim is to post to my MongoDB Atlas database using node, express, mongoose, and Heroku. While a Postman POST request with Raw JSON body: { "title": "heroku post", "description": "post me plsssss" } works f ...

Is the DOMContentLoaded event connected to the creation of the DOM tree or the rendering tree?

After profiling my app, I noticed that the event is triggered after 1.5 seconds, but the first pixels appear on the screen much later. It seems like the event may only relate to DOM tree construction. However, this tutorial has left me feeling slightly con ...

Customizing error messages in Joi validationorHow to show custom

Hi there, currently I am utilizing "@hapi/joi": "^15.1.1". Unfortunately, at this moment I am unable to upgrade to the most recent Joi version. This represents my validation schema const schema = { name: Joi.string() .all ...

Encountering an ENOENT error while attempting to incorporate a style guide into next.js (react)

Recently, I delved into learning next.js and decided to enhance my project with documentation using To kickstart my project, I utilized npx create-next-app After installation and configuration setup, I added the following code snippet: [styleguide.config ...

Unable to Display Embed Request Using Javascript in IE9 and IE10

My website allows users to embed content they create on the site into their own blogs or pages using a series of embeds. Here is the code we provide them: <script src="[EMBED PROXY URL]" type="text/javascript"></script> When this code calls ...

Can a single endpoint provide various JSON responses depending on the user's role?

I seem to be facing a terminology confusion which may be hindering my ability to find a solution. My current project involves creating a REST API within Express and I intend to incorporate roles in the authorization process. What I am curious about is whet ...

What is the best way to retrieve the final entry from a JSON file while using json server with Angular?

I'm currently working with a JSON file where I am making post requests followed by get requests. My goal is to retrieve the latest record in each get request after submitting a post request. For example: [ { "id": 1, "title&qu ...

Efficient way to handle nested variables in templates with Nunjucks or alternative approaches

Recently I've been exploring the world of gulp and nunjucks templating, specifically for creating emails. One challenge I'm facing is figuring out how to call a module/partial and assign different values to its attributes each time it's pro ...

Consolidating repeated data objects found in the response

After receiving an API response, the data looks like this: response = [ { id: 1, val: 'A', date: '28/03/2021', versions: [] }, { id: 1, val: 'B', date: '29/03/2021', versions: [] }, { id: 1, val: 'C', ...