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

CakePHP sidebar list for easy navigation

Looking to create a sidebar list that, when the user clicks on an item, displays all related information in a specific area on the same page. Is AJAX pagination or traditional JQuery the best method for achieving this, or is there another alternative app ...

How to write JSON while maintaining double backslashes

I am looking for a way to save Python data structures as JSON in a Postgresql database. When using json.dumps(), the JSON format is correct, as shown below: >>> import json >>> j = { 'table': '"public"."client"' } &g ...

To close the responsive menu, simply click anywhere outside of the navigation bar

My issue involves a responsive menu with Bootstrap. On desktop, the menu closes fine; however, on the responsive view, I want it to close when clicking outside of the nav menu in any area. Here is my navigation code: <!-- Navigation --> <nav id= ...

Ways to adjust the size or customize the appearance of a particular text in an option

I needed to adjust the font size of specific text within an option tag in my code snippet below. <select> <?php foreach($dataholder as $key=>$value): ?> <option value='<?php echo $value; ?>' ><?php echo ...

Problem with JSON in Spring Boot REST API

Within my spring boot rest application, there is a controller containing the method below. This method utilizes hibernate to retrieve data from an Oracle DB. The problem arises when I call this service, as it returns a HTTP ERROR 500. Strangely, no error ...

"Learn how to convert basic input fields into user-friendly Bootstrap input groups using the power of jQuery

Is there a way to use jQuery to convert my basic input field into a bootstrap input-group like the one shown below? This is how I created the input: <div class='input-group date' id='ff'> <input type='text' class= ...

Sending a message through Discord.JS to a designated channel

Recently diving into Discord.JS, I am struggling to understand how to make my bot send a message to the General Chat when a new user joins. Many examples I've come across suggest using the following code: const channel = client.channels.cache.find(ch ...

Move two markers on Google Maps simultaneously

After researching various articles and posts on Stack Overflow about selecting multiple markers in Google Maps, I have been unable to find a solution for dragging two markers simultaneously. While I've managed to make it work so that one marker can tr ...

Issue with parsing work positions from FaceBook user profiles

Hey there, I'm currently facing an issue while trying to retrieve the name of a work position from Facebook's graph API. This is what I have attempted so far (in JSON): https://graph.facebook.com/me?access_token=ABCDEFGHIJKABCDEFGHIJKABCDE ...

When working with GWT, you can easily attach an event listener to any element on the host page

I am looking to implement a MouseOver event handler for any tag, specifically targeting anchor tags in a legacy HTML page. Following a GWT guide, I successfully utilized their JSNI method to retrieve all anchor tags with some minor adjustments for errors. ...

Passing ngModel from controller to directive in AngularJS

I'm currently working on a project that involves a controller with an attribute directive nested inside of it. This directive requires access to the ngModel of its parent controller. For more context, feel free to check out this Plunkr. Issue at Han ...

Trouble with PHP Ajax form submission due to reCaptcha verification failure

I'm having issues with my form that includes ajax and reCaptcha validation. I can't seem to get the reCaptcha function properly. Every time I try, I keep receiving the error message "Please click the reCAPTCHA box" from sendmail.php (error 400). ...

Retrieving data in String format using Jersey client

I am currently working on developing JUnit tests for a REST client that utilizes Jersey. As part of this process, I require a means to obtain a duplicate of the data being sent to the server in order to run comprehensive tests within JUnit. At present, my ...

Exploring Vue Routing with Regular Expressions

Recently, I integrated a route with a parameter in my Vue project. const routes = [ { path: "/:lang(^$|^es$|^pt$|^cn$)", name: "Home", component: Page, }, { path: "/privacy", name: "Privacy", component: Privacy, }, { ...

Failure to retrieve JSON using $.ajax in JSP

I am attempting to retrieve a JSON Array from a Servlet and populate data into a table. However, the JSON or text is not being received in the JSP despite trying various methods. Below is my JSP code: <%@ page contentType="text/html;charset=UTF-8" lan ...

Utilizing a Variety of Animations with D3 (version 5)

I am currently working on an animation that involves fading out text in a list and collapsing the list when the heading is clicked. However, I am facing a few issues with the code provided in this example. d3.select('.panel-heading') .on(&apos ...

A guide on renewing authentication tokens in the Nestjs framework

import { ExtractJwt, Strategy } from 'passport-jwt'; import { AuthService } from './auth.service'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common&apo ...

Setting background colors for classes based on an array

I have a total of six div elements on a single page, all sharing the same class. My goal is to give each one a unique color from an array I have prepared. I want to avoid any repetition of colors among these divs. Currently, I have managed to assign backg ...

Troubleshooting Issue: MVC 5 validation messages not displaying when using Ajax.BeginForm

Having recently delved into MVC 5, I've encountered some issues that have left me stumped despite my best efforts at troubleshooting. Specifically, my struggle lies in creating a validation mechanism for a user and password list to ensure that all fie ...

Ways to stop VoiceOver from selecting the background content when a modal is open

Is there a way to prevent VoiceOver from reading the content behind a modal? I tried using aria-modal=true, but it seems VoiceOver does not support this feature by default like NVDA and JAWS do. I found more information about this on . According to the in ...