Struggling with navigating JSON data in JavaScript and facing difficulties sorting the array

I am currently facing the challenge of organizing data obtained from an API using JavaScript.

JavaScript Code to Retrieve Data:

function getResults() {
    var url = $.getJSON("http://api.api.com&leagues=SOCENGPRE&lang=en&format=jsonp&callback=?", function(jsondata){;
        for(var i = 0; i < jsondata.length; i++)
            for(var id in jsondata[i]) {
                console.log("ID - " + id);
                console.log("TEAM - " + jsondata[i][id].home_team);
            }
    });
}

Sample of Retrieved Data :

{
    "SOCENGPRE": {
        "league_name": "Barclays Premier League",
        "league_phid": null,
        "league_type": null,
        "fixtures": [
            {
                "id": "64714",
                "code": "SOCENGPRE",
                "event_slug": "west_ham-tottenham-1401290",
                "home_team": "West Ham",
                "away_team": "Tottenham",
            },
            {
                "id": "64711",
                "code": "SOCENGPRE",
                "event_slug": "manchester_u-sunderland-1401286",
                "home_team": "Manchester U",
                "away_team": "Sunderland"
            }

However, my code seems to be failing to produce the desired results.

My objective is to display the ID and Home Team of every game. Any suggestions on why my code isn't working as expected would be greatly appreciated!

UPDATE: I have removed the extra semi-colon but it's still not printing the data for me. UPDATE 2: Regarding the requests for the URL. When I call it in a browser I receive a large result

?({"SOCENGPRE":{"league_name":"Barclays Premier League","league_phid":null,"league_type":null,"fixtures":[{"id":"64714","code":"SOCENGPRE","event_slug":"west_ham-tottenham-1401290","start":"1399117500","home_team":"West Ham","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t523.png","home_team_short":"","away_team":"Tottenham","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t498.png","away_team_short":"","phid":null},{"id":"64711","code":"SOCENGPRE","event_slug":"manchester_u-sunderland-1401286","s...

Link to pastebin for easier reading of the data

Answer №1

Revise your getResults function so that it executes after the JSON data has been parsed, as shown below:

var myDataVar;
$.ajax({
    url: "Enter URL to JSON file here",
    dataType: "text", //If an error occurs, change the type to "text"
    success: function (data) {
        myDataVar = $.parseJSON(data);
        getResults();
    }
});

The above code will store the parsed data from the JSON file into a single variable.

It will then invoke a function to fetch the results, which is defined as follows:

function getResults() {
        var fixturesLength = myDataVar.SOCENGPRE.fixtures.length - 1;
        for (var i = 0; i <= fixturesLength; i++) {
            console.log(myDataVar.SOCENGPRE.fixtures[i].id);
        }
    }

The loop above will display all fixture IDs in the console.

Sample test data used:

{
    "SOCENGPRE": {
        "league_name": "Barclays Premier League",
        "league_phid": null,
        "league_type": null,
        "fixtures": [{
            "id": "64714",
            "code": "SOCENGPRE",
            "event_slug": "west_ham-tottenham-1401290",
            "start": "1399117500",
            "home_team": "West Ham",
            "home_team_phid": null,
            "home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t523.png",
            "home_team_short": "",
            "away_team": "Tottenham",
            "away_team_phid": null,
            "away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t498.png",
            "away_team_short": "",
            "phid": null
        }, {
            "id": "64711",
            "code": "SOCENGPRE",
            "event_slug": "manchester_u-sunderland-1401286",
            "start": "1399125600",
            "home_team": "Manchester U",
            "home_team_phid": null,
            "home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png",
            "home_team_short": "Man U",
            "away_team": "Sunderland",
            "away_team_phid": null,
            "away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png",
            "away_team_short": "",
            "phid": null
        }, {
            "id": "64712",
            "code": "SOCENGPRE",
            "event_slug": "stoke-fulham-1401288",
            "start": "1399125600",
            "home_team": "Stoke",
            "home_team_phid": null,
            "home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t389.png",
            "home_team_short": "",
            "away_team": "Fulham",
            "away_team_phid": null,
            "away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t379.png",
            "away_team_short": "",
            "phid": null
        }]
    }
}

Console output:

64714
64711
64712 

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

Rails application experiencing difficulties in displaying the Raty JS plugin

Encountering issues with the raty js plugin while working on Rails version 5.0. jquery.raty.self-628421be04f36f7a8fa8b9b884c6d7824d6f8bdeba4f172b131f15aa63f713e8.js?body=1:761 Uncaught ReferenceError: jQuery is not defined at jquery.raty.self-628421be ...

Replace Formik with useFormik to streamline your code

I have implemented Formik/Yup for validation on a page that triggers a GraphQL mutation. The code is functioning as expected: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); const [isRemoved ,setIsRemo ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

The functionality of Angular Datepicker is disrupted when scrolling through the page

Coding in HTML <div class="col-5 col-md-3 px-0 daterange-picker"> <div class="form-group"> <div class="input-group"> <input type="text" id="second ...

Difficulty comprehending the fallback for JSON.parse in jQuery.parseJSON

Check out the origin of $.parseJSON function (data) { if (typeof data !== "string" || !data) { return null; } // Remove leading/trailing whitespace for compatibility data = jQuery.trim(data); // Try native JSON parser first ...

Saving Array into JSON Format

Currently, I am in the midst of a research project that involves storing a significant amount of external data. My chosen format for storage is JSON, which is new territory for me. The main requirement is to store a large array of data; however, all JSON e ...

I am interested in running JavaScript code on a page that has been loaded through AJAX

I am struggling to execute the Javascript loaded within an ajax page. Here is the link to my loaded ajax page: https://jsfiddle.net/4dsbry7j/ JS : var xmlhttp = new XMLHttpRequest(); var url = "http://localhost/ajax/find2.php"; xmlhttp.onreadystatechang ...

Ways to retrieve a value from a multidimensional array in PHP

Hey there! I'm currently in the process of building a website using PHP that utilizes a JSON API. My goal is to echo the values of a multidimensional array from my JSON file. "troopsLevels": [ { "value": 5, "globalID": 4000000 }, { "value": 5, ...

Working with JSON Data in C# Classes

I have a JSON file containing a list of items that I would like to convert into properties for a class. Here is an example: { "id": "cmnsz41@fhfitsocj0wgjeajkgbd#4c4mgkf1vwbh_", "displayName": "Archive", " ...

"Enhancing User Experience with Hover States in Nested React Menus

I have created a nested menu in the following code. My goal is to dynamically add a selected class name to the Nav.Item element when hovering, and remove it only when another Nav.Item is hovered over. I was able to achieve this using the onMouseOver event. ...

C# - Swapping Characters with their Unicode Representation

Currently, I am working on an Android application that is designed to read books in JSON format. To create these types of books, I decided to use a desktop application written in C# for its ease of use. In my native language, there are many characters tha ...

What is the best way to trigger the code within my useEffect React hook to execute again upon refreshing the page?

I'm encountering an issue where the value of states is becoming 'undefined' after refreshing the page. Within my useEffect hook, I am generating a random number to select a question object from an array. Everything works smoothly on the ini ...

Guide to creating a Map with typescript

I've noticed that many people are converting data to arrays using methods that don't seem possible for me. I'm working with React and TypeScript and I have a simple map that I want to render as a list of buttons. Here is my current progres ...

Can we accurately pinpoint individual LineSegments in three.js by hovering over them, especially those with unique geometries?

Creating two examples of drawing lines in three.js was quite a fun challenge. One example showcased different geometry and material, while the other kept it simple with just one geometry and material. The demonstration links can be found here: Example 1 an ...

Angular 8: How to Filter an Array of Objects Using Multiple Conditions

I am faced with the following scenario where I need to filter an array of objects based on lineId, subFamily, and status. My current code successfully filters based on lineId, but now I also need to include a condition for subFamilyId. I have two specifi ...

Having trouble connecting to Docker? The webpage at localhost seems to be unresponsive and is not providing any data. Error: ERR_EMPTY_RESPONSE

Currently in the process of mastering docker, kafka, and python. My objective is to leverage python for extracting data from json files and transmitting them to kafka. The setup seems to be functioning properly, but I'm facing challenges with viewin ...

Header stabilization on scroll

On my webpage, I have a table header positioned in the middle of the page. However, due to the length of the page, I am looking for a way to make the header stay fixed at the top of the browser as the user scrolls down. My query is: Is there a method to k ...

Combining selected boxes through merging

Looking to create a simple webpage with the following requirements: There should be 10 rows and 3 boxes in each row. If I select 2 or more boxes or drag a box, they should merge together. For example, if my initial screen looks like this: and then I se ...

Filtering arrays using jq at a nested level

I have noticed that all the demo/examples I've come across are filtering on the first level, but my requirement is to perform array filtering with jq on the second level: { "TheArray": [ { "F1": "V11", "F2": "V12", "F3": "V13" ...

Having trouble loading a JSON file into Spyder

I am new to coding and currently following an interactive tutorial for importing a JSON file with football competition data into Python. Despite my best efforts, I keep encountering error messages at every step of the process, which is starting to frustrat ...