"An in-depth guide on parsing JSON and showcasing it in an HTML format

As part of my order processing, I am saving the order details into a JSON file named order_details.json. Here is an example of how the data is structured:

[{
    "uniqueID": "CHECKOUT_IE01",
    "orderID": "4001820182",
    "date": "06-02-2019 16:55:32.321",
    "cartTotal": "€19.98"
}, {
    "uniqueID": "CHECKOUT_DK01",
    "orderID": "6001825057",
    "date": "06-02-2019 16:56:15.976",
    "cartTotal": "318 DKK"
}]

Now, I want to create an HTML report that will display all this data in a formatted way.

I'm currently unsure about which technology to use for this task. So far, I have attempted to write some JavaScript code as shown below:

var fs = require(['fs']);
var data = fs.readFileSync("D:\\order-detail.json", "utf8");
var data1 = JSON.parse(data);
console.log(data1);
var unique_id = data1[0].uniqueID;  
var order_id = data1[0].orderID;    
var order_date = data1[0].date; 
var cart_total = data1[0].cartTotal;

document.getElementById("uid").innerHTML = unique_id;
document.getElementById("oid").innerHTML = order_id;
document.getElementById("date").innerHTML = order_date;
document.getElementById("ctotal").innerHTML = cart_total; 

and in the HTML file:

<body onload="myFunction()">
<h3>Values from Json</h3>
<div>
<span id="uid"></span>
<span id="oid"></span>
<span id="date"></span>
<span id="ctotal"></span>
</div>

However, I am encountering an error and the functionality is not working as expected. The error message displayed in the console is:

dashboard.html:8 Uncaught TypeError: fs.readFileSync is not a function
    at myFunction (dashboard.html:8)
    at onload (dashboard.html:25)
myFunction @ dashboard.html:8
onload @ dashboard.html:25
require.js:5 GET file:///D:/JSON/fs.js net::ERR_FILE_NOT_FOUND
req.load @ require.js:5
load @ require.js:5
load @ require.js:5
fetch @ require.js:5
check @ require.js:5
enable @ require.js:5
enable @ require.js:5
(anonymous) @ require.js:5
(anonymous) @ require.js:5
each @ require.js:5
enable @ require.js:5
init @ require.js:5
(anonymous) @ require.js:5
setTimeout (async)
req.nextTick @ require.js:5
o @ require.js:5
requirejs @ require.js:5
myFunction @ dashboard.html:7
onload @ dashboard.html:25
require.js:5 Uncaught Error: Script error for "fs"
http://requirejs.org/docs/errors.html#scripterror
    at makeError (require.js:5)
    at HTMLScriptElement.onScriptError (require.js:5)

I am seeking assistance as to what might be wrong in my approach or if there is a better way to achieve this task. Any help would be greatly appreciated!

Answer №1

It seems like there may be some confusion between Node and regular Browser JavaScript. The standard JavaScript language does not include a definition for require; if you encounter it, it's likely because a separate library you're using has implemented it in a different way. One common method for loading data in a browser is through an XMLHttpRequest. Here is a sample code snippet:

loadURL("file:///D:/order-detail.json", onDataLoaded);

function onDataLoaded(data) {
  data = JSON.parse(data);
  var unique_id = data[0].uniqueID;
  var order_id = data[0].orderID;
  var order_date = data[0].date;
  var cart_total = data[0].cartTotal;

  document.getElementById("uid").innerHTML = unique_id;
  document.getElementById("oid").innerHTML = order_id;
  document.getElementById("date").innerHTML = order_date;
  document.getElementById("ctotal").innerHTML = cart_total;
}

function loadURL(url, callBack) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.setRequestHeader("Accept", "application/json");
  xhr.onloadend = onLoadEnd(xhr, callBack);
  xhr.send();
}

function onLoadEnd(request, callBack) {
  return function() {
    var status = request.status;
    var result = String(request.response);
    if (status >= 200 && status < 300) callBack(result);
  };
}

For security reasons, certain browsers like Chrome may block the request. To overcome this issue, consider adding the JSON file to your IIS server (and update file://D:\\order-detail.json to

localhost/addPathHere/order-detail.json
). Here's a helpful tutorial on setting up your local IIS server (assuming you are using Windows).

Answer №2

This method should do the trick.

Swap out ./JSON/order-detail.json with the file path of your JSON data.

$.getJSON('./data.json', function(item) {
  item.forEach(function(data) {
    return [
      document.getElementById("uid").innerHTML += data.uniqueID + "</br>",
      document.getElementById("oid").innerHTML += data.orderID + "</br>",
      document.getElementById("date").innerHTML += data.date + "</br>",
      document.getElementById("ctotal").innerHTML += data.cartTotal + "</br>"
    ];
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Values from Json</h3>
<div>
  <span id="uid"></span>
  <span id="oid"></span>
  <span id="date"></span>
  <span id="ctotal"></span>
</div>

Answer №3

Utilizing the NodeJS pattern within client-side JavaScript is a common practice. When working on the front-end, you have the ability to directly import a JSON file using jQuery.

$(function(){
        $.getJSON('order-detail.json',function(data){
            $.each(data,function(i,order){

             //your code implementation here..
             // You can access data elements such as order.uniqueID and order.orderID

            });
        }).error(function(){
            console.log('error');
        });
    });

The .json file should be accessible under your domain just like CSS, JS, and image resources. Keep in mind that you cannot access it through a full path such as C:\yourpath\file.json

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

How can I easily send JSON using PhpStorm/WebStorm REST client?

Within the PhpStorm / WebStorm version of 2017, there exists a REST client that allows us to send requests and analyze responses. Typically, when I send a POST request using the easy form in the UI to create request parameters, the parameters are formatte ...

Guide to generating an array entry for every line of a text file in node.js

Struggling with converting each line of a text file into an array entry in node.js The array I am working with is named "temp." The code below successfully prints out each line: var temp = []; const readline = require('readline'); const fs = re ...

Having trouble with adding a class on scroll?

My challenge is to extract the header from this website, by adding an additional class when the user scrolls at a position greater than 0. I thought it would be easy, but Java always presents problems for me. Here’s the code I came up with: <!DOCTY ...

Adding external JSON data to a plain HTML document can be achieved through the process of

I have been experimenting with extracting data from an API in JSON format, but I am struggling to figure out how to convert the JSON tags into HTML elements. You can view a sample of the JSON data here. Does anyone know how to transform this JSON into DI ...

Remove any objects from the array that have empty values when filtered

I am facing a challenge with filtering objects in an array. Each object contains a title and rows, where the rows also have a risk value (like P1, P2, P3, etc.). My goal is to extract only the rows that have a risk equal to P1 while skipping any objects th ...

Is there a method to store only a portion of the string object in async-storage?

Is there a way to save only part of the string object into async-storage? For example, if the "result.userPrincipalName" contains "[email protected]", I want to save only the "bob23". What is the best method to achieve this? await AsyncStorage.setIt ...

The function `Object.entries().map()` in TypeScript does not retain the original data types. What changes can I make to my interface to ensure it works correctly, or is there a workaround

Working with this interface: export interface NPMPackage { name: string; description: string; 'dist-tags': { [tag: string]: string; }; versions: { [version: string]: { name: string; version: string; dependencie ...

Combining PHP JQuery Dialog with Datatables results in a sleek design loss

Recently, I encountered an issue with my code. I have a file called incident_view.php which pulls data from the database and displays it using Datatables. Everything was working fine until I tried to open this page in a JQuery dialog on another page called ...

Determine in JavaScript if one date occurs exactly one week after another date

Currently, I am tackling a date comparison task for our application. The main objective is to compare the Start Date inputted by the user with the Operator/Region Effective Date, which signifies when a new list of product prices becomes valid. Our aim is t ...

What is the best way to implement a Cascading Async Select feature using @atlaskit/select library?

I recently delved into React and I'm currently exploring how to create a Cascading Async Select (for example, selecting Country then City) using @atlaskit/select. As per the documentation, I utilized the option loadOptions in the initial Async Select ...

Modifying the theme of the Angular UI-Bootstrap datepicker

I am currently facing an issue with my angular datepicker, which is appearing oversized and covering almost 30% of the screen. Additionally, there are large gaps between the dates in the calendar view. After some investigation, I believe this problem may ...

Adjusting characteristics in Angular dynamically through JSON

Having trouble changing the value of [icon]="reactAtom" to use a JSON value? Need assistance in updating the [icon] value based on the 'featureItem' received from the parent component. HTML <div> <fa-icon [icon]="reactAtom" class="i ...

The paragraph text should dynamically update upon clicking a button based on JavaScript code, however, the text remains unchanged despite attempts to modify it

I recently started learning JavaScript and wanted to update the content of a paragraph when a button is clicked. However, I encountered an issue where this functionality doesn't seem to work. <body> <p id="paragraph">Change Text on cl ...

Modifying the color of a header through clicking on a specific anchor link

My goal is to create a fixed side nav bar on my webpage with an unordered list that links down the page using anchors. In addition, I want to dynamically change the color of an h2 element based on which item in the fixed nav bar is clicked on. For instan ...

What is the method for specifying a JSON object within a DOM element's `data` attribute?

In an attempt to store JSON data within a dataset attribute, I encountered the following HTML structure: The appearance of the HTML is as follows <div data-switch="true" data-json="{'key1': 'value 1'}, {'key2': 'valu ...

When hovering over items in the navigation bar, the entire bar expands seamlessly

I've spent countless hours trying to troubleshoot an issue with my dropdown menu that expands whenever I hover over it. The bar stretches out to accommodate the list of dropdown contents and then reverts back to normal when I move my cursor away. My a ...

Is there a way to retrieve a label's text using their class name within a loop?

I have multiple labels sharing the same classname, each with different text. My goal is to iterate through them and extract the text they contain. Here is the example markup: <label class="mylabel pull-left"> Hello </label> <label class="m ...

How the React Component Class Executes OnChange Event in a Closure

When working on my React code, I found myself creating a closure by calling "onChange." class CityInput extends React.Component { constructor( props ){ super( props ); this.state = { city : "", country : "" ...

In Vue, when utilizing Firestore, the .where method doesn't seem to be returning any results even though they do exist in

As a newcomer to Firestore, I'm working on a query to display chat messages that update in real-time when new ones appear. However, I'm facing an issue where only messages from the current user's school should be visible. If I omit the .wher ...

Creating Personalized Checkboxes for Internet Explorer Versions 7 and 8

I am currently in the process of implementing custom checkboxes for my website. Everything is functioning smoothly on browsers such as IE9 and other modern ones. However, I am encountering issues with IE8 and 7. Below is a snippet of my CSS code: input[typ ...