What is the best way to showcase arrays in a JSON document?

I'm working on a basic AJAX code to show a JSON file stored locally using this HTML, but I keep getting an 'undefined' error. I'm opting for JavaScript instead of JQuery since I haven't delved into it yet; hoping my code is syntactically correct. Thanks in advance!

<script>

        function loadJSON()
{
           var data_file = "language.json";
           var http_request = new XMLHttpRequest();
           try{
              // Opera 8.0+, Firefox, Chrome, Safari
              http_request = new XMLHttpRequest();
           }catch (e){
              // Internet Explorer Browsers
              try{
                 http_request = new ActiveXObject("Msxml2.XMLHTTP");
              }catch (e) {
                 try{
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                 }catch (e){
                    // Something went wrong
                    alert("Browser does not support this.");
                    return false;
                 }
              }
           }
           http_request.onreadystatechange  = function(){
              if (http_request.readyState == 4  )
              {
                // Javascript function JSON.parse to parse JSON data
                var jsonObj = JSON.parse(http_request.responseText);

                // jsonObj variable now contains the data structure and can
                // be accessed as jsonObj.name and jsonObj.country.
                document.getElementById("language").innerHTML =  jsonObj.language;
                document.getElementById("edition").innerHTML = jsonObj.edition;
              }
           }
           http_request.open("GET", data_file, true);
           http_request.send();
        }

        </script>
    </head>
    <body>
        <table border="1">
        <tr><th> language </th> <th> edition </th></tr>
        <tr><td> <div id="language"></div> </td><td> <div id="edition"></div> </td>     </tr>
        </table>
        <button type="button" onclick="loadJSON()"> Load JSON </button>
    </body>
</html>

Here's the JSON content I want to showcase in a table via AJAX.

{
"books":    [
    { "language": "Java" , "edition" :"second"},
    { "language": "C++" , "edition" :"fifth"},
    { "language": "C" , "edition" :"third"}
    ]
}

Answer №1

To properly display the books from the jsonObj.books array, you should iterate through it like so:

var table = document.getElementById("books_table"); // assuming: <table id='books_table'...
for(var i in jsonObj.books) {
 var book = jsonObj.books[i];
 table.innerHtml += '<tr><td> <div>'+book.language'+</div> </td><td> <div> '+book.edition'+</div> </td></tr>';
}

The jsonObj.books variable is indeed an array.

for(var i in jsonObj.books)

This loop goes through the indexes of the array.

 var book = jsonObj.books[i];

It then retrieves the specific 'book' object at position 'i' within the array.

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

What could be causing the lack of updates for a watched object in vue?

Although there are many similar questions on this topic, mine has a unique twist. After delving into reactivity in depth, I feel like I have a solid grasp of the concept. However, one thing continues to baffle me: Summary: Why does a watched property det ...

Attaching a $UI element to a <div> tag with JQuery may result in unexpected errors and issues

Attempting to connect SagePayments card elements to the paymentDiv. Followed their sample project for guidance, but encountering issues with populating the elements when running the program with a custom Sandbox merchantID and merchantKey. Chrome's de ...

"Error: imports are undefined" in the template for HTML5 boilerplate

After setting up an HTML5 Boilerplate project in WebStorm, I navigate to the localhost:8080/myproject/src URL to run it. Within the src folder, there is a js directory structured like this: libraries models place.model.ts place.model.js addr ...

Dealing with undefined or null values when using ReactJS with Formik

Issue Resolved: It seems that Formik requires InitialValues to be passed even if they are not necessary. I'm currently working on a formik form in React, but every time I click the submit button, I encounter an error message stating "TypeError: Canno ...

merge two structures to create a unified entity

I have been searching in vain, can you please advise me on how to combine these two simple forms into one? I want it to be like a box with a select option and a button. The challenge for me is merging the two different actions, ".asp", into one script fo ...

Validation of textfields using React.js

Currently, I am working on implementing a validation feature in ReactJS. Specifically, I have a field named "name" and my requirement is that every time a name is entered, it must be equal to or greater than 2 characters. The validation works fine when t ...

Having trouble with jQuery.validate.js while using type="button" for AJAX calls in an MVC application

I have come across several questions similar to mine, but I haven't found a solution that fits my situation in MVC, so I am reaching out for help. I am a beginner with MVC and I am utilizing jQuery AJAX to invoke a controller method for data insertio ...

Implementing the fetch API with radio buttons in a React Native application

I found a useful package for radio buttons called react-native-flexi-radio-button. Currently, I'm working on displaying API results within radio buttons. The API response provides 4 options, and my goal is to render text alongside the corresponding ra ...

Having trouble displaying JSON response in Firefox console with Django

Code Snippet: from .views import get_data app_name = 'javascript' urlpatterns = [ path('', views.index, name='index'), path('api/data', get_data, name='api-data'), ] Views.py: from django.http ...

The counterpart to Ruby's `.select{ |x| condition }` in Javascript/ React.js would be to

This javascript function in React.js utilizes a for loop to determine the opponent team: getOpponentTeam: function(playerTeamId){ var matches = this.state.matches; var player_team = this.state.player.team.name for (i in matches){ if (matches[i]. ...

Implementing conditional button visibility in Angular based on user authorization levels

I've been experimenting with the following code snippet: <button ng-if="!isAuthenticated()" ng-click="deleteReview()">Delete</button> In my JavaScript, I have: $scope.isAuthenticated = function() { $http.get("api/user ...

HTML code is not displayed within the ng-template

After passing JSON data in the correct format from my Laravel controller, I'm trying to display it recursively using Angular. However, the HTML inside ng-template is not being rendered. What could be the issue? Note: I've replaced the default An ...

How to use ngModel directive in Angular to select/unselect dynamically generated checkboxes and retrieve their values

Currently, I am working with a dataset retrieved from an API and dynamically creating checkboxes in my HTML page using the DataView component from PrimeNG. My objective is to implement a feature where users can select or deselect all checkboxes with a cli ...

Using jQuery to make an AJAX request to a PHP script

Curious about how to capture the value of a checkbox when it is checked and then store it in a PHP session if possible. Unsure if this can be achieved, hence reaching out here for assistance! Here's an excerpt from the code I am working with: ...

Retrieve the output of a function once the function has completed

I'm facing an issue where I need to wait for a function to return a value from my MySQL table before using it as a return for my const ProjektNameIntentHandler. Here is the relevant code snippet: const ProjektNameIntentHandler = { canHandle(handlerIn ...

My goal is to use both jQuery and PHP to automatically populate the dropdown list

Here is my PHP code for executing a query: $host = "localhost"; $user = "root"; $pass = "abc123"; $databaseName = "class"; $con = mysql_connect($host,$user,$pass); $dbs = mysql_select_db($databaseName, $con); $result = mysql_qu ...

Passing a service into a directive results in an undefined value

Can someone help me understand why a service I am injecting into a directive is returning undefined in certain instances? If you would like to take a look at the code, here is a plunker link: https://plnkr.co/edit/H2x2z8ZW083NndFhiBvF?p=preview var app = ...

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

Create a receipt by utilizing jQuery with dynamically generated inputs

Is there a way to insert the descriptions and amounts of invoice items into the receipt, similar to the due date? The input for this section is dynamic with multiple rows that can be added or deleted. I'm considering using a counter that increments e ...

Having trouble transferring a variable from getJSON data to PHP

I am encountering an issue with my jQuery getJSON method when trying to pass data to PHP. Strangely, I am unable to pass a variable. In another part of my code, passing the variable works fine. Additionally, hardcoding the string or using a valid variable ...