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

POWER QUERY - Data in a JSON request with incorrect structure

I have encountered an error while developing a request in Power BI's Power Query. The error message is as follows: Invalid format payload in a JSON request. Here is the code snippet: let URL1 = "example/login", POST = [ #"Conten ...

Javascript malfunctions upon refreshing the div

After updating data with an ajax function and refreshing the div, I encountered an issue where the jQuery elements inside the div break. How can this be resolved? function getURLParameter(name) { return decodeURIComponent((new RegExp('[?|&]&apo ...

Personalized 404 Error Page on Repl.it

Is it possible to create a custom 404-not found page for a website built on Repl.it? I understand that typically you would access the .htaccess file if hosting it yourself, but what is the process when using Repl.it? How can I design my own 404-not found p ...

The functionality of jQuery click events seems to be disabled on the webpage, however, it is working perfectly fine on jsFiddle

After thoroughly checking the js tags and ensuring everything is properly closed, it's frustrating when the JavaScript suddenly stops working. The code functions perfectly in JSFiddle, leading me to believe that the issue may lie with something I&apos ...

using document references in puppeteer's evaluate/waitFor function

I'm feeling a bit lost when it comes to understanding the document reference in puppeteer's evaluate method. The official documentation shows some code that includes this reference within a waitFor function in a node script. I get that these line ...

Is it possible to transform an arrow function into a regular function?

Currently, I am working my way through the AJAX type ahead course in Javascript 30 by Wes Bos. As I progress through this course, I have made a conscious effort to minimize my use of ES6 features for the sake of honing my skills. If you want to see the fi ...

Increasing the spacing between lines when a column value changes while exporting a DataFrame to a .txt file

I have a dataset structured like this: df = Sentence # Word POS Tag join 0 Sentence: 1 Thousands NNS O Thousands O 1 Sentence: 1 of IN O of O 2 Sentence: 1 demonstrators NNS O demonstrators O ...

What steps can be taken to enhance the functionality of this?

Exploring ways to enhance the functionality of JavaScript using the underscore library. Any ideas on how to elevate this code from imperative to more functional programming? In the provided array, the first value in each pair represents a "bucket" and the ...

Python script utilizing curl to make requests to a URL through an API

As a novice Python scripter, I encountered a challenge when trying to integrate a link shortening service. The API documentation provided by the service is in JSON format and requires URL calls using curl. Due to my limited experience, I struggled with i ...

What significance does comparing two arrays hold in the realm of Javascript?

While working in my node.js REPL, I have created 4 arrays: a = [1,2,3], b=[], c=[4,5], d=null (although d is not actually an array). I decided to compare them directly like this: > b = [] [] > a > b true > b > a false > a > c false & ...

Switch the visibility of a div tag using Next.js

Script export default function Navigation(){ let displayMenu = false; function toggleMenu() { displayMenu = !displayMenu; } return ( <> <button onClick={toggleMenu}>Toggle Navigation</button> {/*This code sh ...

What is the process for deleting an attribute from the RequestSpecification/FilterableRequestSpecification body?

Hey there, I've been working on a simple method that takes a String argument as a path or "pointer" to attributes in JSON, and this method is meant to remove those specified attributes. The challenge I'm facing is that while I can retrieve the ...

Is there a way for me to extract a smaller segment from an ID label?

I am working on a web development project and I have a set of buttons within a specific section. Each button has an id in the format of #balls-left-n, where n ranges from 1 to 15. My goal is that when a user clicks on one of these buttons, I want to extra ...

Transform an array of arrays object with multiple depths into an array of objects

Having some difficulty with the conversion of an array of arrays-like object into an array of objects. The reduce method is being used, and it successfully converts the array data to an object for the first set of arrays. However, on the second iteration, ...

Update the image source through an AJAX call

I've experimented with various methods to update an image src using an AJAX request. The new URL is obtained through the AJAX call, and when inspecting the data in Developer Tools, the 'DATA' variable contains the correct URL. However, the i ...

When creating a dynamic page number using JavaScript during a print event, the height of an A4 page is not taken into

While creating my A4 invoice using HTML, CSS, and JS, everything appears correctly in the print preview. However, I am encountering an issue where the page number is not aligned properly and extra empty pages are generated automatically. Below is a snippe ...

"Sweet syntax" for assigning object property if the value is true

In the project I'm working on, I find myself dealing with a lot of parsing and validating tasks. This often results in 5-10+ lines of code like if(value) object.value = value. I considered using object.value = value || (your favorite falsy value) app ...

Why do I keep encountering a null window object issue while using my iPhone?

Hey there! I've got a React game and whenever the user loses, a new window pops up. const lossWindow = window.open( "", "", "width=500, height=300, top=200, left = 200" ); lossWindow.document.write( & ...

Enhance your React application by making two API requests in

Below is the React Component that I am working on: export default function Header () { const { isSessionActive, isMenuOpen, isProfileMenuOpen, setIsMenuOpen, closeMenu, URL } = useContext(AppContext) const [profileData, setProfileData] = useState({}) ...

Tips for programmatically choosing images from a Google Photos collection?

Currently, I am attempting to use code in the console to automatically choose a photo from a Google Photos Album while browsing. I've tried this method so far: const photo = document.getElementsByClassName('p137Zd')[0].parentElement photo. ...