Accessing data from a JSON file within a JavaScript program

Here's the scenario:

I have created a function that reads my JSON file and returns the value found at the end.

This is how my files are organized:

https://i.sstatic.net/TMeXVHNJ.png

Below is my script.js file:

async function readJSONFile(path) {
    const [filePath, jsonPath] = path.split('|');

    try {
        const response = await fetch(filePath);
        if (!response.ok) {
            throw new Error(`Network response was not ok: ${response.statusText}`);
        }
        const jsonData = await response.json();
        const keys = jsonPath.split('/');
        let value = jsonData;
        for (const key of keys) {
            if (Array.isArray(value) && !isNaN(key)) {
                value = value[parseInt(key)];
            } else {
                value = value[key];
            }
            if (value === undefined || value === null) {
                return undefined;
            }
        }

        return value;
    } catch (error) {
        console.error(`Failed to read JSON file: ${error}`);// There's an error
        return undefined;
    }
}

const path = 'Items.json|Data/taxValue';
readJSONFile(path).then(result => console.log(result));  // Should print 1.15

And here is my JSON file in case it is needed:

{
    "Data": [
        {
            "taxValue": 1.15
        }
    ],
    "Fruits": [
        {
            "name": "apple",
            "cost": 1.59,
            "tax": true,
            "itemId": 12345,
            "ect...": 0
        }
    ],
    "Others": [

    ]
}

I expected to read the file but encountered an error,
'

script.js:25 Failed to read JSON file: TypeError: Failed to fetch
',
I am unsure about how to fix this issue, which is why I am seeking help.

Answer №1

When attempting to load an HTML file in a web browser and utilize JavaScript to access a JSON file within your file system, it's important to note that browsers do not have the capability to directly access the file system. By simply providing the fetch API with a file name, it will append the host as a suffix to the file name you provided ("file:///D:/some-dire/Items.json"), causing confusion as browsers only support http or https protocols and not FTP. This leads to the error message "failed to fetch".

To address this issue:

Consider setting up a development server in Node JS that can serve both static files (such as index.html and style.css) as well as JSON files like Items.json over http or https using the fetch API.

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

Converting a string into a list extracted from a text document

Within a file, the data (list) is structured as follows: [5,[5,[5,100,-200],200,-400],300,-500] Upon reading this file in an angular application, the contents are converted into a string object like so: "[5,[5,[5,100,-200],200,-400],300,-500]" Is there ...

Execute bulk updates in Odoo using Xmlrpc for multiple rows at once

I need assistance updating multiple records of "sale.order.line" products in Odoo Xmlrpc. for (let i = 0; i <sell.products.length; i ++) { var inParams = []; inParams.push ([value1 [i]]); //id to update in ...

Passing JSON data from a Ruby controller to JavaScript in Rails 6.1 - Tips and Tricks

I am attempting to transfer JSON data from my database to the front-end in order to manipulate it using JavaScript. Initially, I created some temporary JSON data in my home.html.erb file like this: <%= javascript_tag do %> window.testJSON_data = ...

Sequenced jQuery promises with the ability to halt execution

Currently, I am in the process of writing API code that involves multiple layers of wrapping around $.ajax() calls. One crucial requirement is to allow users to cancel any request, especially if it is taking too long. Typically, canceling a request can b ...

Able to display the value when printing it out, however when trying to set it in setState, it becomes

Within my form, there's a function that receives the value: _onChange(ev, option) { console.log(option.key) // Value of option key is 3 this.setState({ dropdownValue:option.key }) // Attempting to set state with 'undefined' as ...

When using jQuery, the .change() function will only be triggered after the user clicks a button or

Looking for assistance with an unusual issue in my JavaScript/jQuery code. The jQuery .change() function on a simple text input element only triggers when I click somewhere on the page, open the Chrome console, or press a key on the keyboard. It doesn&apo ...

When sending an AJAX request to a URL, can I verify in the PHP page whether it is a request or if the page has been accessed?

In order to enhance security measures, I need to prevent users from accessing or interacting with the php pages that will be utilized for ajax functionality. Is there a method available to determine if a page has been accessed through an ajax request or b ...

Converting CSV into an Array of Hash Tables

Currently, I am working on parsing a CSV file and creating an array of hashes. While I initially implemented this using my own code, I feel that it may not be the most efficient solution. My aim is to utilize the CSV-Parser library, but so far, I have only ...

Codeigniter code to retrieve dynamic data in a select box

I am trying to implement a functionality where selecting an option from one dropdown will dynamically populate the options in another dropdown based on the selection. I believe I need to use an onchange function, but I'm unsure how to retrieve data fr ...

Modify the date input format in PHP, Bootstrap, Javascript, and HTML5

My current date input format is mm/dd/yyyy and I would like to change it to dd/mm/yyyy. Does anyone know how to do this? I am using Bootstrap 4. Here is the code snippet: <!DOCTYPE html> <html> <head> <title></title> ...

Additional forward slash appears within a JSON array

I am working on a project involving nestable drag and drop functionality. When I drag and drop tiles, it generates an array in a textarea that looks like this: [{},{"id":267},{"id":266}]. However, when I post this array on the action page, it gets posted ...

Utilizing Jquery to auto-scroll when an element reaches the top of

I have arrows positioned at the end of sections on my website that I want users to be able to click on in order to scroll to the next section. The issue I am facing is that while the first click works, subsequent clicks do not result in scrolling even thou ...

Problem with npm during Nativescript command line installation

I'm having trouble setting up Nativescript for developing iOS apps in Javascript. When I tried to install it using the command below: npm i -g nativescript I encountered the following error message: module.js:327 throw err; ^ Error: Cannot ...

Can you explain the distinction between these two constructor designs?

Function ConstrA () { EventEmitter.call(this); } util.inherits(ConstrA, EventEmitter); as opposed to Function ConstrA() {} util.inherits(ConstrA, EventEmitter); Is the use of EventEmitter.call(this) necessary in this context? ...

Show a Pop-Up When a Key is Pressed

My website popup features a 'Close' button in the top right corner, a text section with a background image, and a 'Print' button at the bottom. The popup automatically appears when the page loads. However, once closed, there is currentl ...

Transferring json.dump to StringIO in Python 3

I am currently in the process of migrating an application from Python 2 to Python 3. While running Python 2.7, I encountered an issue when updating the code to pass pylint --py3k tests. The problem lies within the following function: def json_resource_fil ...

Having trouble with Sequelize Single Instance not functioning properly after using Module.exports?

Here is my Sequelize Code snippet for database connection: var sequelize = new Sequelize('db-name', 'user', 'pwd', { host: 'XXX.XX.XX.XXX', dialect: 'mysql', pool: { max: 50, m ...

Transition the background image into view upon hover

I'm looking to enhance my jQuery code that changes the background image when hovering over text by adding a fade-in effect. Here's the current code I have: $(document).ready(function(){ $("#anatomyNow").hover(function(){ $("#bg").cs ...

Utilize data retrieved from an API to customize the appearance of buttons through the combination of React and Sass styling techniques

I retrieved data from an API and used it to create a list of buttons. The data I received includes names and color codes. { name: "bob", colorCode: "#DC7472" }, { name: "ben", colorCode: "#69DCD1" }, { name: &q ...

Is it possible to extract the value from the JSON response using this.responseText?

Having trouble extracting data from a json response This is the HTML code I am using. index.html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head ...