Using a JSON file as a database for a project featuring HTML, CSS, and Vanilla JavaScript

Our task was to create a project that exclusively utilized JSON files for data storage. The data structure we were working with resembles the following:

[
{
    "aircraftName": "Boeing 747",
    "departDate": 1640173020000,
    "departure": "Metro Manila, Philippines",
    "destination": "Kuala Lumpur, Malaysia",
    "estDate": 1640777820000,
    "id": "Flight_0001",
    "occupancy": 4,
    "onboardPassengers": [
        { "passenger": "Person 1", "seat": "A1" },
        { "passenger": "Person 2", "seat": "A2" },
        { "passenger": "Person 3", "seat": "B4" },
        { "passenger": "Person 4", "seat": "C5" }
    ],
    "passengers": 15,
    "status": "available",
    "depDate": "2021-12-22"
},
{
    "aircraftName": "Boeing 868",
    "departDate": 1640875620000,
    "departure": "Singapore, Singapore",
    "destination": "Tokyo, Japan",
    "estDate": 1640875620000,
    "id": "Flight_0002",
    "occupancy": 5,
    "onboardPassengers": [
        { "passenger": "Person 1", "seat": "A1" },
        { "passenger": "Person 2", "seat": "A2" },
        { "passenger": "Person 3", "seat": "B4" },
        { "passenger": "Person 4", "seat": "B5" },
        { "passenger": "Person 5", "seat": "A3" }
    ],
    "passengers": 10,
    "status": "available",
    "depDate": "2021-12-30"
},
{
    "aircraftName": "Airbus A350",
    "departDate": 1640875860000,
    "departure": "Jakarta, Indonesia",
    "destination": "Bangkok, Thailand",
    "estDate": 1640875860000,
    "id": "Flight_0003",
    "occupancy": 0,
    "onboardPassengers": [],
    "passengers": 15,
    "status": "available",
    "depDate": "2021-12-30"
},
{
    "aircraftName": "Airbus A220",
    "departDate": 1640876040000,
    "departure": "Tokyo, Japan",
    "destination": "Beijing, China",
    "estDate": 1641624840000,
    "id": "Flight_0004",
    "occupancy": 0,
    "onboardPassengers": [],
    "passengers": 15,
    "status": "available",
    "depDate": "2021-12-30"
},
{
    "aircraftName": "Airbus A220",
    "departDate": 1640876040000,
    "departure": "Tokyo, Japan",
    "destination": "Beijing, China",
    "estDate": 1641624840000,
    "id": "Flight_0005",
    "occupancy": 0,
    "onboardPassengers": [],
    "passengers": 10,
    "status": "available",
    "depDate": "2021-12-30"
}]

We encountered an issue as we weren't sure how to manipulate and access a JSON file using JavaScript for our browser-based application rather than a Node.js environment. Any suggestions on how to address this challenge would be greatly appreciated.

Answer №1

To retrieve information from your JSON file, use the following code snippet

let data;
function fetchData() {
    if (data) return Promise.resolve(data);
    return fetch("./data.json")
        .then(response => {
            data = response.json();
            return data;
        }).catch(err => console.log(err));
}

fetchData().then(result => {
    console.log(result);
});

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 method to implement foreach within a Vue select component?

Is there a way to utilize a Vue loop within a select box in order to achieve the following category and subcategory options layout: +news -sport -international +blog In PHP, I can accomplish this like so: @foreach($categories as $cat ...

Is there a way to transform a circular structure into JSON format?

I retrieved data from the database and now I need to format it, but I encountered the following error: TypeError: Converting circular structure to JSON --> starting at object with constructor 'NativeConnection' | property ' ...

Using NodeJS/Express to deliver a JSON response in ISO-8859-1 format

I've encountered a challenge with the encoding of JSON data from an API I built using Node and Express. The web application that needs to read this data only accepts ISO-8859-1 encoded JSON, causing some difficulty. Despite following the methods outl ...

I must determine whether the contents of an array exceed zero

THE SUMMARY: I have three value numbers for an array. If the total addition of the array's elements is greater than 0, I need to display "el funcionamiento no es infinito", otherwise "es infinito". It seems that it's not working because I belie ...

Images are suddenly encircled by a mysterious border

On my wordpress website, I encountered a strange issue with some photos. Specifically, an image of a cross in a circle is getting a weird border around it, but only on certain resolutions (such as width:1506). Despite inspecting the element, I couldn' ...

Angular-UI keypress event allows users to interact with components and

I am facing challenges while using the keypress feature in the following code snippet- <div ng-controller="GBNController"> ... <input id="search-field" type="text" placeholder="JSON Query" ng-model="queryText" ui-keypress="{enter: foo()}"/> .. ...

pretending to make an ajax call using jQuery

To enhance the user experience of file upload, I have implemented a fake ajax request. When the user clicks submit, the form disappears, a loading graphic appears, and after a few seconds, the page refreshes to display the newly uploaded image. However, e ...

What is the best way to completely clear $rootScope when a user signs out of my application?

In my development work, I frequently find myself using $rootScope and $scope within controllers and services. Despite searching through numerous Stack Overflow answers for a solution to clear all $scope and $rootScope values, such as setting $rootScope t ...

Manipulating strings within strings with JavaScript

It's been a strange discovery I made while working with JavaScript. Whenever I try to assign a two-word string to a CSS property, like setting the fontFamily property of an HTML element to "Arial Black", it ends up looking something like thi ...

JavaScript code to copy a specified column through the last column, and then paste it down to the last row

I have limited experience with JavaScript and I've been putting together the code I need by searching online resources and watching videos. My goal is to set multiple columns in row 4, starting from column 18 to the last column, as the active cells fo ...

JavaScript Truthy and Falsy Tutorial on Codecademy

Could someone kindly clarify why this code is not functioning correctly? let defaultName; if (username) { defaultName = username; } else { defaultName = 'Stranger'; } This code snippet was found in the JavaScript section on Codecademy, but a ...

How to iterate through a JavaScript array in reverse order using a for loop and the array's length property

When looking to iterate through an array with the values [8,7,6,5,4], some may wonder why a for loop using the length of 5 continues to function even though there is no element at index 5 in the array. for(let i=array.length;i>=0;i++){ //do somethin ...

Creating a webpage with a left panel and draggable elements using JavaScript/jQuery

As someone new to Javascript/jQuery, I have been given the task of creating a web page with elements in a "pane" on the left side that can be dragged into a "droppable" div area on the right side. The entire right side will act as a droppable zone. I am u ...

utilizing an ajax request to clear the contents of the div

When I click on Link1 Button, I want to use ajax to empty the contents in the products_list div <button type="w3-button">Link1</button> I need help with creating an ajax call that will clear the products in the product_list when the link1 but ...

css element remains stationary and in view

Issue at hand: I have created a logo file named .art-obj1631017189 and I am looking to fix its position. It appears to work fine, but when scrolling down and it encounters the content section, my object falls behind the content (item-layout). I desire to ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

Stay dry - Invoke the class method if there is no instance available, otherwise execute the instance method

Situation When the input is identified as a "start", the program will automatically calculate the corresponding "end" value and update the page with it. If the input is an "end", simply display this value on the page without any modifications. I am in th ...

How can I detect a DOM element mutation based on a CSS selector, and if this is possible, how can it be accomplished?

Imagine there's a website with a specific HTML element. It seems that this element has the same class during the DOMContentLoaded event as it does during the load event. However, after the load event, this class (and possibly the ID and other HTML att ...

Transforming a JavaScript component based on classes into a TypeScript component by employing dynamic prop destructuring

My current setup involves a class based component that looks like this class ArInput extends React.Component { render() { const { shadowless, success, error } = this.props; const inputStyles = [ styles.input, !shadowless && s ...

Utilizing CSS naming conventions to bring order to class inheritance

I'm a bit unclear about the rationale behind using this specific CSS structure: h2.class-name It seems like you could simply use .class-name and apply that class to the h2 element: <h2 class="class-name">Title thing</h2> Unless it&apos ...