"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

Waiting for asynchronous subscriptions with RxJS Subjects in TypeScript is essential for handling data streams efficiently

Imagine having two completely separate sections of code in two unrelated classes that are both listening to the same Observable from a service class. class MyService { private readonly subject = new Subject<any>(); public observe(): Observable&l ...

Enhancing readability with JSON Spirit's elegant formatting

I have a C++ program that receives a lengthy JSON string containing thousands of symbols. I want to use JSON Spirit to print it with multiple lines and proper indentation for debugging purposes. Here is an example of what I would like to achieve: { "abc ...

Querying SQL Server by extracting JSON data from the database tables

Currently, I am in the process of constructing a testcafe web automation project that utilizes a data-driven framework. My tools of choice include NPM/node.js and Visual Studio Code. Within this project, I have both a JSON file and a SQL query. The challen ...

Using JQuery, you can easily add a new row right after the row that you have

I need to insert a new row after the selected row, but my current code inserts the row at the end if no row is selected. Is there a way to fix this issue? strGridId = update_GridID(strGridId); var grid = jQuery('#' + strGridId); var columnModel ...

Sharing data between two Angular 2 component TypeScript files

I'm facing a scenario where I have two components that are not directly related as parent and child, but I need to transfer a value from component A to component B. For example: In src/abc/cde/uij/componentA.ts, there is a variable CustomerId = "sss ...

I'm experiencing difficulty accessing the correct identification number for my questions on the website

Hi, I'm currently developing a website using Meteor where users can post questions and receive answers. I want to implement a feature that allows users to delete their own questions. When I try to directly pull the ID of the question and delete it, it ...

What methods can be implemented to ensure uniform usage of a single library version among all developers?

Our team utilizes Angular and Visual Studio Code for development, while GitHub serves as our code repository. While this setup has been effective, we recently encountered an issue where one developer had a different version of a particular library. This di ...

Pop-up with a unique MediaBox design

Last week, I inquired about window pop-ups and have been brainstorming alternatives. One idea I had is to use mediabox/lightbox style pop-ups. Would it be feasible to create a link that opens a mediabox window off to the side when clicked? Users could dra ...

Looping through arrays within objects using NgFor in Angular 2/JavaScript

I have a custom object with data that I am iterating through using ngFor. Within this object, there is an array component that I also want to iterate through in a <li></li>. Currently, the output appears as one complete string within each < ...

Generate the Xpath for the mentioned href element to use with Selenium Webdriver

I need help creating the Xpath for a specific href element using Selenium webdriver with only IE browser. The HTML code I am working with is as follows: I am looking to find the Xpath for: . Can someone assist in generating the correct Xpath expression ...

AngularJS triggers after the completion of Ajax requests

How can I implement AJAX within Angular AJAX? In my Angular setup, it looks like this: Index.html MyApp.controller('MainController', function($scope, $http, $location , $compile) { $scope.content_middle = 'Welcome'; ...

The hydration error in next js is causing this code to malfunction

Why am I encountering a hydration error with this code in NextJS? The Items variable is an array of ReactNode's. Any suggestions for an alternative approach? I've searched extensively for information but haven't found anything related to Nex ...

React checkbox remains checked even after uncheckingIs this revised version

I am currently working on a React application where I display an array of matches as a list of rows. Each row contains two athletes, and users can use checkboxes to predict the winner for each match. Only one athlete per row can be checked. To keep track o ...

What exactly does form.getHeaders(); mean?

Attempting to streamline the upload process, I have come up with the following code: var http = require('http'); var request = http.request({ method: 'post', host: 'https://www.ws-ti.4bank.com', path: '/img/create ...

Establish a predetermined selection for a drop-down menu

How can I set a default value for a dynamically filled dropdown menu featuring all 12 months in KnockoutJS? I want the default value to be the current month. This is how I am populating the dropdown with information: self.setMonthData = (data ...

Updating nested forms in Angular 4

The nested form structure I am working with is a 'triple level' setup: FormGroup->ArrayOfFormGroups->FormGroup At the top level (myForm): this.fb.group({ name: '', description: '', q ...

Manipulate the color of the parent text using a button nested within

I am working on a script that adds a button to div elements with the class name "colors". When the button is clicked, the text color of the parent element will change to a specified color. However, I'm facing an issue where it only changes the last el ...

What is the best way to modify a current state object without causing an endless loop of redirects?

const useCase = (argument) => { const [value, setValue] React.useState(argument) React.useEffect(() => setValue({...value ...argument), [argument, value, setValue]) } The above code is currently causing an infinite loop due to setting the stat ...

Exploring the intricacies of initializing a JavaScript function

I recently inherited a large JavaScript file from a previous developer, and I'm trying to decipher some of the key sections. Here is the complete code: $(function () { var homepage = (function () { // Main functionalities are defined he ...

How to display the name of the parent object using JavaScript's prototypal inheritance

I've been delving into JavaScript prototypal inheritance and the prototype property, and I decided to create a fiddle to gain a deeper understanding. However, I'm struggling to comprehend why my example isn't functioning as expected. In the ...