In JavaScript, when parsing JSON, the data seems to always be undefined

I'm currently attempting to parse a JSON file from an online source. Feel free to check out the link yourself. Unfortunately, no matter what I try, I keep getting 'undefined' when trying to access the data. All I want is some kind of output from this JSON file. Specifically, I'm struggling to retrieve the list of names ('nm') in the file. Despite my efforts, it consistently returns undefined.

    $.ajax(
    {
        type: 'GET',
        url: 'http://mysafeinfo.com/api/data?list=englishmonarchs&format=json',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function(r)
        {
            alert(r.example);
        }
    });

Answer №1

The information retrieved from the API comes in the form of an array containing objects like these.

[{
  name: "Edward the Elder",
  country: "GB",
  house: "House of Wessex",
  years: "899-925"
}, {
  name: "Athelstan",
  country: "GB",
  house: "House of Wessex",
  years: "925-940"
}]

One way to loop through the array of objects is using $.each

success: function(response)
{
  $.each(response, function(index, obj){ // iterating over each object

       console.log(obj.name); // <---- accessing the name property of each object

  });
}

Answer №2

You haven't made any updates to the result set.

This version is more concise and easier to understand.

$.getJSON("http://mysafeinfo.com/api/data?list=englishmonarchs&format=json", function (data) {

    $.each(data, function (index, value) {
        alert(index + ": " + value.nm);

    });
});

http://jsfiddle.net/5skony7y/2/

If you open the Chrome console, you'll observe the following:

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

Tips for stopping special characters from being copied and pasted into a number field

My goal is to ensure that only numbers can be copied and pasted into the 'number field'. By preventing the copy and paste of characters like 'e', '+', '-', and '.', I can ensure that the number field only c ...

Is it necessary for ajax to delay displaying the output until a PHP script has completed?

Currently, I am utilizing ajax to execute a basic PHP script that echoes numbers. My main goal is to determine whether ajax will display each echo as it occurs or if it will wait until the entire script is completed before displaying any results. <?php ...

Refreshing Symfony2 values dynamically with ajax without the need for page reload

Let me start by saying that I am not a front-end expert, and this is my first attempt at working with ajax. My goal here is to update and display the new value without having to refresh the entire page. I only want to refresh the input field and its values ...

Should the method of creating a Dropdown with Angular be considered a poor practice?

I've recently dived into Angular and successfully created my first dropdown using it, which is working great. However, I'm a bit concerned about the number of comparisons being made and wondering if this approach is considered bad practice. The ...

Implementing a comprehensive Node application with a fully stacked npm and package.json structure

If there's a repository with both backend (Node/Express) and frontend client, the structure might look like this: ├── build ├── config ├── coverage │ └── lcov-report ├── dist │ └── static ├── server ( ...

How to Iterate Through Two JSON Payloads Using Nested Loops in Python and Generate a Dictionary from the Output

Hey Pythoineers! Need some help deciphering this output: Aim - My code involves two loops iterating through two JSON payloads. The first loop groups all Department keys into a list of unique values. The second loop iterates through the keys collected in t ...

Is there a way to retrieve a JSON result from an API call using jQuery (or plain JavaScript) without relying on Ajax?

As someone new to JS and jQuery, I am working on building a key-value map from an API call that returns an array of key-value pairs. [{"key":"191","value":244}, ... , {"key":"920","value":130}] I have created the following ajax code in my attempt to achi ...

How to retrieve a variable or map from an HTTP request in Angular 2+?

In my service, I have the functionality to either store an object for access in other components or request data from a web API and return it in a map. Example of retrieving data from objectService: get(): any { if (this.object == undefined || this.o ...

Exploring the power of AngularJS by nesting elements within multidimensional arrays and revealing their content through a simple

Check out this fiddle for accurate information, though it may not be visually positioned correctly: http://jsfiddle.net/LhRfq/ I am working with a three-dimensional JSON object. The first level of array items should be displayed in a single line, which ...

Using PySpark to append a nested array to an existing JSON file

Looking for help with a JSON file in Spark? Here's the structure: root |-- dialogueData: struct (nullable = true) | |-- dialogueID: string (nullable = true) | |-- dialogueLength: double (nullable = true) | |-- speakerChanges: long (nulla ...

Running a Node JS application concurrently with an Express API connected to MongoDB

Here's my current project plan: I've created a small Node app that fetches data about the stock market from an API and then stores the data in a Mongo DB (which is already up and running). My next step is to create an API that will allow other se ...

Function compilation did not succeed in the module

I've put together a MERN (MongoDB, ExpressJS, React, Node) project using express-generator (express myNewApp). Within a react component, I have implemented this ES6 code snippet: onChange = (event, { newValue }) => { // Line 53 this.setSt ...

How can unicode (%u2014) be handled in JavaScript or C#/.NET?

While browsing through the vast expanse of the internet (specifically on a review site like Rotten Tomatoes), I stumbled upon %u2014. This particular string reminded me of something I once encountered in JavaScript. Although I can't quite recall if it ...

OrbitControls: modifying the position and overall size of a 'guide' object

I am currently working on managing a 3D object that visually represents the target controls for easier understanding of rotation and zooming... If you want to see an example, check out this sample I created with an AxisHelper indicating the target with co ...

The script is stuck displaying the existing records, failing to update with any new ones

Kindly refrain from offering jQuery advice. This script is created to display additional database records when you scroll down to the bottom inside a div named results-container. The issue I'm encountering is that the same data keeps appearing. I&ap ...

Listening for Angular 2 router events

How can I detect state changes in Angular 2 router? In Angular 1.x, I used the following event: $rootScope.$on('$stateChangeStart', function(event,toState,toParams,fromState,fromParams, options){ ... }) In Angular 2, using the window.addEv ...

Send data from a PHP form with various input types using JavaScript and AJAX

I need to submit a form with various fields, including multiples checkboxes selection and some hidden input fields via AJAX and then replace the HTML content with the response. I decided to use JavaScript/AJAX for this process, but did I make any mistakes? ...

Retrieve relationship data from tables as JSON format, where there is a one-to-many connection

These two tables are derived from the diagrams. Each question may have multiple answers. I am looking to retrieve data by question ID in JSON format, similar to the structure below: var initialData = [ {question_id: "1", Description: "Danny", Status: ...

Issues encountered with implementing a custom search feature using AJAX in jQuery UI Autocomplete

Here is the response from my JSON data: [{"value":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4a5a0a9adaa84a5a0a9adaaeaa7aba9">[email protected]</a>"},{"value":"<a href="/cdn-cgi/l/email-protection" class ...

Troubleshooting: Problems with Angular 2's [hidden] and *NgIf functionalities

My table displays a green circle if data is available in the gegevensAanwezig variable, which contains a school name, school code, and various booleans (Entreetoets, Eindtoets, etc) to indicate data availability. <tr *ngFor="let g of gegegevens ...