Converting API-generated JSON data into an HTML table

My goal is to retrieve time and temperature data for all seven days from a JSON response obtained after querying an external weather API, specifically the Open Meteo service. I am struggling to populate an HTML table with this data.

Below is the code snippet I have been working on:


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<style>
    th{ 
        color:#fff;
            }
</style>


<table class="table table-striped">
    <tr  class="bg-info">
        <th>time</th>
        <th>temperature</th>
      
    </tr>

    <tbody id="myTable">

    </tbody>
</table>

<script>
    var myArray = [
    
    ]

    $.ajax({
        method: 'GET',
        url: 'https://api.open-meteo.com/v1/forecast?latitude=44.32&longitude=23.80&start_date=2022-11-30&end_date=2022-12-06&daily=temperature_2m_max&timezone=GMT',
        success:function(response){
            myArray = response.daily
            buildTable(myArray)
            console.log(myArray)
        }
    })

    function buildTable(data){
        var table = document.getElementById('myTable')
        
        for (var i = 0; i < data.length; i++){
            var row = `<tr>
                            <td>${data[i].time}</td>
                            <td>${data[i].temperature_2m_max}</td>
                            
                       </tr>`
            table.innerHTML += row
            
        }
    }

</script>

The JSON response that I receive

Raw--

{"latitude":44.3125,"longitude":23.8125,"generationtime_ms":0.3180503845214844,"utc_offset_seconds":0,"timezone":"GMT","timezone_abbreviation":"GMT","elevation":106.0,"daily_units":{"time":"iso8601","temperature_2m_max":"°C"},"daily":{"time":["2022-11-30","2022-12-01","2022-12-02","2022-12-03","2022-12-04","2022-12-05","2022-12-06"],"temperature_2m_max":[5.9,6.1,8.1,9.5,9.3,7.3,4.3]}}

Parsed ---

{
"latitude": 44.3125,
"longitude": 23.8125,
"generationtime_ms": 0.3180503845214844,
"utc_offset_seconds": 0,
"timezone": "GMT",
"timezone_abbreviation": "GMT",
"elevation": 106,
"daily_units": {},
"daily": {
"time": [
"2022-11-30",
"2022-12-01",
"2022-12-02",
"2022-12-03",
"2022-12-04",
"2022-12-05",
"2022-12-06"
],
"temperature_2m_max": [
5.9,
6.1,
8.1,
9.5,
9.3,
7.3,
4.3
]
}
}

Answer №1

Give this a shot

function createTable(info){
        var myTable = document.getElementById('temperatureTable')
        
        for (var j = 0; j < info.time.length; j++){ 
            var newRow = `<tr>
                            <td>${info.time[j]}</td> 
                            <td>${info.temperature_2m_max[j]}</td>                           
                       </tr>`
            myTable.innerHTML += newRow
            
        }
    }

Answer №2

Successful implementation, much appreciated!

function generateTable(data){
        var table = document.getElementById('myTable')
        
        for (var j = 0; j < data.days.length; j++){ 
            var row = `<tr>
                            <td>${data.days[j]}</td> 
                            <td>${data.temperature_high[j]}</td>                             
                       </tr>`
            table.innerHTML += row
            
        }
    }

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

Error: The function semrush.backlinks_refdomains does not exist as a valid function

Hey there! So I've been working with the SEMRUSH API and encountered an issue when trying to retrieve data using backlinks_refdomains and backlinks_refips. However, when I called the domain_rank function, it responded in JSON format without any proble ...

Unable to connect dynamic information in Angular 8 component

Error encountered during dynamic component loading DynamicBuilderComponent.ngfactory.js:198 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: The expression has changed after it was checked. Previous value: 'ng-pristine: true'. Current ...

Tips on how to extract particular JSON information from an HTTP request by utilizing jQuery

I am attempting to extract the exchange rate from the JSON http response below by using jquery. Assume that jquery has already been included within the <head></head> tags. { "Realtime Currency Exchange Rate": { "1. From_Currency Co ...

Exploring the use of dynamic arrays in C through reading and storing data

I need assistance in implementing a dynamic array based on the content of a file, with the intention to use it with the qsort() method. Although I have managed to determine the number of lines that meet certain criteria in the file, I am struggling with ...

When initially selecting a value from the dropdown, the return value displayed is [object Object]. However, after selecting an option, it changes and works properly. Any suggestions on how to

Within my Angular 7 application, I am encountering an issue when attempting to populate a dropdown menu within a form. The dropdown always displays an undefined value at first, which prevents me from validating it using the required attribute. It is puzzli ...

Converting a deeply nested dictionary into a pandas dataframe

I've been struggling to convert a deeply nested dictionary into a pandas DataFrame. I attempted to use a recursive function, similar to the one below, but my issue is that I lose track of the previous key while iterating over a KEY. I also experimen ...

Tips on programmatically filtering angular lists

Is there a way to programmatically filter an Angular list? I'm currently working on a project where I need to filter subcategories by clicking on categories. For example, when clicking on "Drinks," I want to display items like Coke, Fanta, Pepsi... ...

Off Canvas left navigation menu using Bootstrap

I am working on creating a responsive layout for a webpage using Bootstrap. On larger displays, such as desktop resolutions, I want the webpage to show the header and left navigation as normal. However, when the site is resized to that of tablets or mobile ...

Establish a route to extract a particular item from an array

Looking to extract specific values from a JSON data set, as shown in the highlighted image. Can anyone guide me on how to navigate the path and retrieve these desired values? The code I currently have fetches all IDs, but I'm interested in accessing t ...

What is the best way to create a clickable background for a modal window?

I am looking to add a chatbox feature to my website and have been utilizing Bootstrap Modal for this purpose. My goal is to keep the modal open even when the user clicks outside of it, while still allowing them to interact with the background of the websi ...

Automatically refresh a pair of pages in sequence

Seeking advice on how to execute the following steps in JavaScript: - Pause for 120 seconds - Access http://192.168.1.1/internet-disconnect (in an iframe or similar) - Pause for 3 seconds - Access http://192.168.1.1/internet-connect - Repeat Here is ...

Sending 3D array indexes as arguments to a function

Here is the complete code I have so far, if you need to refer to it. I am working with a 3D array that stores high and low temperatures for specific days and months. I am required to pass this array through the following function: double average_array(in ...

Encountering an error when trying to change the input form which reads "Cannot read property of '1' undefined"

I am currently learning how to use React and I encountered an issue with changing the state of a form based on user input. To better explain my problem, I have provided a demo here. The error message Cannot read property '1' of undefined is being ...

Wait for the scope value to become available before executing the directive or div

I have a unique directive created for SoundCloud that necessitates the SoundCloud URL. The URL is fetched from the database using the $http service, but the issue arises when the div for the directive is loaded before the URL value is defined. The code fo ...

In React JS, if you encounter the error "localStorage is not defined," here's a guide on how to troubleshoot and

What causes the issue of localStorage not being defined? const [bookmark, setBookmark] = useState([]); const { showBookmark, setShowBookmark } = useContext(Context); const addToBookmark = (id) => { if (!bookmark.includes(id)) setBookmark(b ...

Struggling to load app.css, main.js, and other files while using an Express server

I'm struggling with my code setup. Essentially, I have the following piece of code: var express = require('express'); var app = express(); var server = require('http').Server(app); app.get('/', function(req,res){ res.s ...

Mirroring an array in Java

I'm a beginner in Java and I have been given a task to develop an application. I encountered an issue that I can't seem to overcome. The problem involves updating an array element using reflection (the application selects a public array to updat ...

Why is the script from URL "http://.../js/myscript.js" not executing as expected after being fetched?

Is it possible to have the server run a JavaScript file specified in a URL, such as "http://.../js/script_name.js", and return the result instead of just displaying the source code? I am assuming that the server is using node.js. ...

Arrange data in PostgreSQL by the total of calculated numbers

There is a table called tips, and its structure is defined as shown below: CREATE TABLE tips ( tip_id bigserial NOT NULL, tip text NOT NULL, author text NOT NULL, post_date bigint NOT NULL, likers character varying(16)[], dislikers character v ...

Accessing List Property in Neo4j Procedure

In my label, there is an array property named "LEG_OV_ARR" which contains long data type values. For example: The array values for LEG_OV_ARR are [297, 107, 0, 0, 0, 0]. I need to retrieve these array values in my procedure. This is the code snippet ...