Using JavaScript to execute a JSON parse function will not work

I am currently working on this code and would appreciate any assistance. I'm trying to retrieve and parse data from my listApp.json file to display a list with one link. As a beginner, I could use some guidance.

<script type = "text/javascript">
// If the .js files are linked correctly, we should see the following output inside the JavaScript Console
console.log("starting...");

// Retrieving the .json file and applying the function  
var json;
  // Running the function when the document is ready
  $(document).ready(function(){
    // Using standard jQuery ajax technique to load a .json file
    $.ajax({    
      type: "GET", 
      url: "include/listApp.json", 
      dataType: "json",
      success: jsonParser 

    });
  });

// Parsing function
function jsonParser(data) {
    JSON = data;

    $(JSON).find("games").each(function (){
      games = $(this);
      var name = $(games).find("name").text();
      var url = $(games).find("url").text();
      var id = $(games).find("id").text();

      console.log(name);
      
      $("#myList").append('<li>'+ "<a href ="+url+">"+name+"</a>"+'</li>');
      $('#myList').listview('refresh');
      $("#pages").append('<div data-role="page" id = "'+ id +'"><img src = '+ url +'> test</div>');

      });

    }

</script>   

Answer №1

If the variable data is an object, you have the ability to access the games array within it by using data.listApp.games. You can then loop through this array utilizing the $.each() method. Inside the callback function of the loop, the game object will be passed as the second parameter, allowing you to retrieve its properties using the member operator.

function jsonParser(data) {
    $.each(data.listApp.games, function (i, game) {
        var name = game.name;
        var url = game.url;
        var id = game.id;

        console.log(name);
        // Appends list + link + name
        $("#myList").append('<li>' + "<a href =" + url + ">" + name + "</a>" + '</li>');
        $('#myList').listview('refresh');
        $("#pages").append('<div data-role="page" id = "' + id + '"><img src = ' + url + '> test</div>');
    });
}

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

Using jQuery to retrieve a file that has been uploaded through an input field with the type of 'file'

I am looking to extract the file that has been uploaded using an <input type='file'> tag. Currently, when I use $('#inputId').val(), it only retrieves the name of the file, not the actual content of the file itself. I came acros ...

Create a custom hook that encapsulates the useQuery function from tRPC and provides accurate TypeScript typings

I have integrated tRPC into a project that already has API calls, and I am looking to create a separate wrapper for the useQuery function. However, I am facing challenges in getting the TypeScript types right for this customization. My Objective This is w ...

Unclear value of button when being passed

In my Welcome.html file, I am attempting to send the value of a button to a function that simply logs that value. This function is located in a functions class that has been imported into my welcome.ts file. <ion-content padding id="page1"> <h1 ...

Customizing the style of an element in Vue depending on the size of the window

I am struggling to update the appearance of an HTML element when the window size is below 500px. Currently, I have a computed property that sets a background-image for the element. I attempted to use an if statement within the computed property to check if ...

Exploring the capabilities of referencing MongoDB documents with the populate method in Node.js

I have been working on referencing in Node.js using the populate method, but I am unsure about how exactly it works. In my code, I am creating a reference to the user collection from my child collection. I have two collections - one for children and anothe ...

Troubleshooting a JavaScript Error in AngularJS Module

I created a Module called "app" with some helper functions in the file "scripts/apps.js": angular.module('app', ['ngResource']).run(function($scope){ $scope.UTIL = { setup_pod_variables: function (pods){...} ... }); Now, I want to ...

Unexpected Disconnection of AJAX Response Moments Before Rebooting the Raspberry Pi

I currently have a LAMP server set up on my Raspberry Pi 4, where a web page is utilizing an AJAX call to trigger a php script that initiates a reboot of the pi. The php script echoes a JSON string response back to the web page indicating that it is prepar ...

Obtain geographic information using a JSON fetch from a map

I am facing an issue while integrating Laravel API data into React. Although I can see the JSON data in the console after fetching it, I encounter an error when I try to display it in a table for listing. The error states that my .map function is not recog ...

Unusual display of feedback text in Bootstrap 4

When I directly copied this code snippet from Bootstrap 4: <div class="form-group has-danger"> <label class="form-control-label" for="inputDanger1">Input with danger</label> <input type="text" class="form-control form-contro ...

What is the best way to output information to a webpage using json_encode in PHP?

I've implemented a button on my webpage that triggers a database call using ajax, so the page can dynamically display the data without requiring a refresh. Oddly, when I click the button and inspect the source and network tab, everything seems to be f ...

Steps for rearranging the order of CSS grid layout

Could you assist me in implementing a grid layout that fulfills these specific criteria? I'm unsure of how to proceed, so any guidance would be greatly appreciated. https://i.sstatic.net/vBtXc.png When there are more than 9 items, the current layout ...

Efficiently sending a cookie with an Axios POST Request

My request is not receiving a cookie even after trying various solutions like withCredentials. I have pasted the most recent code here, can anyone spot what might be missing? var cookie_for_data = "token=test"; var host = "http://localh ...

Problems with the firing of the 'deviceready' event listener in the PhoneGap application

Utilizing vs2012, I have been working on a PhoneGap application. Within this application, the following JavaScript code is being used: document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // alert("hh") ...

Top spot for locating resolve functions in AngularJS

I'm currently in the process of setting up resolves for my admin panel routes and I'm pondering the best way to store them without cluttering my router with methods. Here's what I have so far: when('/admin', { templateUrl: &ap ...

Issues arise when attempting to determine the accurate dimensions of a canvas

Looking at my canvas element: <canvas id='arena'></canvas> This Element is set to fill the entire website window. It's contained within a div Element, both of which are set to 100% size. I attempted running this script: var c ...

Configuring Chart.js in Laravel to Initialize with Value of Zero

I'm struggling to set my Chart.js chart to zero in my Laravel project. Could someone please help me with this? $chartjs = app()->chartjs ->name('lineChartTest') ->type('bar') ->size(['width' => ...

Error message displayed for invalid date format in Material UI (dateTime picker) after form submission

I recently integrated the Material Ui DateTime picker into my form. However, upon submitting the form, I encountered the following error: Invalid Date Format Image In my React app, I am utilizing JSON Server to store data. Displayed below is the outpu ...

Is there a way to match a string with information stored in a JSON file?

I have a snippet in my index.js that looks like this: if ('and' == trueWords) { console.log('Success!') } else { console.log('Failure!') } Below is the content of my json file: { "and": 1 } Appreciate your help! ...

How can you utilize jQuery to export multiple-page HTML content into a PDF document?

I'm having trouble exporting HTML to PDF using jQuery, especially when the HTML content spans multiple pages in the PDF file. Below is my current code snippet: $("body").on("click", "#downloadPDF", function () { html2canvas($('#dow ...

What is the best way to identify duplicate keys in fixed JavaScript objects?

My approach so far has been the following: try { var obj = {"name":"n","name":"v"}; console.log(obj); // outputs { name: 'v' } } catch (e) { console.log(e); // no exceptions printed } My goal is to detect duplicate keys within a ...