What are some methods to showcase JSON information using only JavaScript either from a local JSON file or a web server?

Hello, I am new to working with JSON and I am curious to know if it is possible to use only JavaScript (without any frameworks) to present all the data from a JSON file in a table format.

Preferably, I would like to load the file locally, but if using a web server to fetch the file is necessary, that is fine too.

[
    {
        "id": "bitcoin",
        "name": "Bitcoin",
        "symbol": "BTC",
        "rank": "1",
        "price_usd": "8088.05",
        "price_btc": "1.0",
        "24h_volume_usd": "9825660000.0",
        "market_cap_usd": "137294244348",
      
    
    }, 
     {
        "id": "siacoin",
        "name": "Siacoin",
        "symbol": "SC",
        "rank": "36",
        "price_usd": "0.0144578",
        "price_btc": "0.00000178",
        "24h_volume_usd": "17730600.0",
        "market_cap_usd": "487999542.0",
        }
    ]

The example above showcases the type of data within my file. Any assistance on how to achieve this would be greatly appreciated. Thank you.

Answer №1

If you prefer not to rely on frameworks, consider using XMLHttpRequest.

To implement this method, you will still need to run a local web server, such as http-server.

Assuming you have three essential files in the same directory: index.html, script.js, and data.json.

index.html

<script type="text/javascript" src="script.js"></script>

script.js

function loadJSON(callback) {

    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'data.json', true); //'data.json' represents the relative path of the .json file
    xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
            callback(xobj.responseText);
        }
    };
    xobj.send(null);
}

(function() {
    loadJSON(function(response) {
        var actual_JSON = JSON.parse(response); //You can now use the actual_JSON variable to construct your table
        console.log(JSON.stringify(actual_JSON, null, 2));
    });
})()

data.json

[
    {
        "id": "bitcoin",
        "name": "Bitcoin",
        "symbol": "BTC",
        "rank": "1",
        "price_usd": "8088.05",
        "price_btc": "1.0",
        "24h_volume_usd": "9825660000.0",
        "market_cap_usd": "137294244348"
    },
    {
        "id": "siacoin",
        "name": "Siacoin",
        "symbol": "SC",
        "rank": "36",
        "price_usd": "0.0144578",
        "price_btc": "0.00000178",
        "24h_volume_usd": "17730600.0",
        "market_cap_usd": "487999542.0"
    }
]

It's worth mentioning that I eliminated the trailing comma in market_cap_usd.

Once your local server is set up, simply open a web browser and navigate to localhost:port_number

(Commonly utilized ports are 3000 or 8080).

Credits: https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript

Answer №2

A great way to kick things off is by diving into the world of ES6 Fetch API...

Be prepared for surprises with Fetch. It may not catch everything you expect.

fetch(url) // Invoke the fetch function with the API url as a parameter
.then(function() {
    // Handle the data retrieved from the API
})
.catch(function() {
    // Run error-handling code if the server returns any errors
});

Explore more about using Fetch API on MDN

Answer №3

Answering your inquiry on a larger scale, the response is affirmative. This concept forms the basis of many frameworks that offer resources for building html data tables using javascript (capable of loading xml, json, csv, and more). By presenting a table in html, you can employ javascript to alter the html structure. Frameworks streamline this procedure, saving you the effort of starting from scratch.

Answer №4

A traditional method of displaying data in a table, assuming the JSON data is already available.

<table id="myTable" border="2">

</table>

<script>

var data = [
    {
        "id": "bitcoin",
        "name": "Bitcoin",
        "symbol": "BTC",
        "rank": "1",
        "price_usd": "8088.05",
        "price_btc": "1.0",
        "24h_volume_usd": "9825660000.0",
        "market_cap_usd": "137294244348",


    }, 
     {
        "id": "siacoin",
        "name": "Siacoin",
        "symbol": "SC",
        "rank": "36",
        "price_usd": "0.0144578",
        "price_btc": "0.00000178",
        "24h_volume_usd": "17730600.0",
        "market_cap_usd": "487999542.0",
        },
     {
        "id": "siacoin 3",
        "name": "Siacoin 3",
        "symbol": "SCD",
        "rank": "32",
        "price_usd": "0.0144578",
        "price_btc": "0.00000178",
        "24h_volume_usd": "17730600.0",
        "market_cap_usd": "487999542.0",
        }
    ];
function displayData(){
  var table = document.getElementById("myTable");
  var tableInfo = '';
  data.forEach((item, index)=> {
    tableInfo += "<tr><td>"+item.id+"</td><td>"+item.name+"</td><td>"+item.symbol+"</td><td>"+item.rank+"</td></tr>"
  })
  table.innerHTML = tableInfo;
}

displayData();
</script>

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 is the best way to invoke the first exported function from the second exported function?

I am looking to create a file containing four or five exported functions. exports.firstFunction = function() { // some code }; exports.secondFunction = function() { // need to call firstFunction }; My issue is that I want the second expo ...

Having difficulty transitioning a function with a promise from JavaScript to TypeScript

I am currently in the process of transitioning my existing NodeJS JavaScript code to TypeScript for a NodeJS base, which will then be converted back to JavaScript when running on NodeJS. This approach helps me maintain clear types and utilize additional fe ...

Adjust the field of view of the camera in ThreeJS

I'm currently working on adjusting the field of vision for a camera without having to create a new one. So far, I've successfully achieved this for the position using the following code: camera.position.set() Now, I'd like to implement a s ...

The statement "document.getElementById('grand_total_display').innerHTML = "Total is : $"+variable;" is causing issues in Internet Explorer versions 6 and 7

document.getElementById('grand_total_display).innerHTML = "Total is : $"+variable; seems to be causing an error specifically in IE6 and IE7 Within my HTML, I have an element <li> identified as grand_total_display which contains some existing te ...

Element on webpage "Expands" When Scrolled into Visibility

After posting a question on Stack Overflow, I noticed discrepancies between the element dimensions reported by Chrome Inspector and Selenium WebDriver. While Chrome Inspector showed w = 979, h = 1961, Selenium returned dimensions of 979 and 1461 respective ...

Understanding the Parameters for discord.js Slash Commands

I am currently working on a calculation that involves using parameters input through a slash command. While entering the parameters works without any issues, I am facing difficulty in retrieving them. The current code is resulting in an error TypeError: ...

Understanding JSON: Pairing Keys with Values

Is it possible to match the keys with the corresponding values in a JSON file? Check out this JSON file here View an image of the data structure I am referencing The keys are located in the "fields" section, while the values can be found in the "data" s ...

Invoke `setState` function in contexts outside of React framework

Is the following approach guaranteed to work correctly within React v18 semantics? The "rules of hooks" only address calling the hook within the component, with no mention of whether it's acceptable to call the dispatcher returned from the ...

Convert a Java object instance into a JSON format via serialization

Is there a way to convert any Java object instance into JSON format? Specifically, I am looking to serialize a group of InetAddress objects. { "Client1":addr1 "Client2":addr2 } In the above example, addr1 and addr2 represent instances of the Inet ...

Is it possible to convert the useMemo function into a useReducer hook implementation?

While I've figured out how to switch from using useState to useReducer, I'm now curious if there's a similar approach for transitioning from useMemo? I've been troubleshooting some code that's causing unnecessary renders because o ...

Ways to transfer GET form information to Express?

I am working on a form that needs to pass parameters correctly <form action="./search" method="GET"> <div class="form-group text-center"> <input type="text" name="keyword" placeholder="Search Term" /> ...

Error: 'window not defined' or 'document not defined' encountered while importing a module in Next.js

I'm working on integrating a Wysiwyg editor into my web application. However, I encountered an error when trying to import the editor module. I tried using both react-draft-wysiwyg and react-quill. The former resulted in a "window not defined" error, ...

The TypeScript declaration for `gapi.client.storage` is being overlooked

When I call gapi.client.storage.buckets.list(), TypeScript gives me an error saying "Property 'storage' does not exist on type 'typeof client'." This issue is occurring within a Vue.js application where I am utilizing the GAPI library. ...

Difficulty with Horizontal Mousewheel Scrolling

Struggling to implement a horizontal scrolling feature (via mousewheel) for both containers in the code below. I want this feature to be easily applied to any future container creations as well. <body> <style> #container { display: flex ...

How to successfully transfer input data from a dialog to a controller using jQuery and Grails

As a newcomer to Grails and jQuery, I recently created a jQuery dialog following this example: http://jqueryui.com/dialog/#modal-form The goal is to open a dialog, input data, and have it displayed in a dynamic table on the main page. Once all entries are ...

Guide for retrieving the maximum length of an input field using JavaScript

Is it possible to retrieve the maxlength of an input field using JavaScript? <input type="password" id="password" maxlength="20" > I attempted to do this, however it only returns undefined console.log(document.getElementById("password").maxlength) ...

The Angular ViewportScroller feature appears to be malfunctioning in the latest release of Angular,

TestComponent.ts export class TestComponent implements OnInit, AfterViewInit { constructor( private scroller: ViewportScroller, ) {} scrollToAnchor() { this.scroller.scrollToAnchor('123456789'); } } HTM ...

Struggling to customize checkbox design using HTML and CSS

Why am I unable to style HTML checkboxes with CSS? No matter what I try, the appearance of the checkboxes remains unchanged: Here is the HTML code: <input type="checkbox" id="checkbox-1-1" class="regular-checkbox" /> <nput type="checkbox" id ...

The addClass() method seems to be malfunctioning following an ajax request

My current project involves setting up an AJAX call that is triggered when a user clicks on an anchor link. Once the AJAX operation is successful, I want to dynamically add a class to the specific anchor that initiated the call. The script itself seems to ...

Creating a Flask Python REST API that allows for optional JSON parameters to be passed in during a POST

I am currently in the process of developing a REST API using Flask that is responsible for adding photos to a database. The database abstraction is done through the PhotoModel Class. When the API receives an HTTP POST request in JSON format, it contains a ...