Learning the process of accessing a JSON file from a different directory

I am faced with a straightforward folder structure, it looks like this:

project  
│
└───data
│     file.json
│    
└───js
      test.js

My goal is to access the content of file.json within the test.js file in order to perform some additional back-end operations. Here's an example of a JSON file (the actual content is generic):

{"key1": 50, "key2": 6, "key3": 20,
"ke4": 18, "key5": 38, "key6": 30}

Thus far, my attempt has been:

var request = new XMLHttpRequest();
request.open("GET", "< path >", false);
request.send(null)
var my_JSON_object = JSON.parse(request.responseText);
alert(my_JSON_object.result[0]);

Unfortunately, this approach did not produce the desired outcome.

I have referred to these posts: post and one. They address similar issues, but they are outdated.

Consequently, my question is: What is the correct method for achieving this task, and is there a more modern approach (e.g., fetch) available?

Answer №1

Even though the answers provided are a bit outdated, the old code is still functional and addresses half of your question. I personally don't mind using deprecated code as long as it gets the job done. The jQuery implementation you mentioned may not be cutting edge, but it functions just like the other solutions:

 $.getJSON('data/file.json', function(data) {
     console.log(JSON.stringify(data));
 });

In addition, the code snippet from your example won't work because the asynchronous nature of the operation is not being properly accounted for. When dealing with asynchronous tasks, it's crucial to define a callback function to execute once the file is loaded:

function readTextFile(file, callback) {
   var request = new XMLHttpRequest();
   request.overrideMimeType("application/json");
   request.open("GET", "< path >", false);
   request.onreadystatechange = function() {
       if (request.readyState === 4 && request.status == "200") {
          callback(request.responseText);
       }
   }
   request.send(null);
}

// Usage:
readTextFile("data/file.json", function(text){
   var my_JSON_object = JSON.parse(text);
   console.log(my_JSON_object);
   alert(my_JSON_object.result[0]);
});

Answer №2

In my opinion, the solution you provided seems suitable. However, I suspect that there might be an issue with the file path. Instead of using :

$.getJSON('data/file.json', function(data) {
     console.log(JSON.stringify(data));
 });

Wouldn't it make more sense to use:

$.getJSON('./data/file.json', function(data) {
     console.log(JSON.stringify(data));
 });

Please take note of the "./" at the beginning of the file path.

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 to prevent the parent element from scrolling when changing the value of a number input by scrolling

Within a container with fixed dimensions and scroll bars that appear when the content size exceeds the container, there is a form. This form contains an input of type "number" which allows changing its value using the mouse wheel. The issue arises when at ...

The graph visualization fails to update properly even after attempting to redraw it

A new feature has been added to the website that allows users to zoom into specific areas of graphs created using Flot objects. An array containing all the Flot objects on the screen has been implemented, and the selection plugin is being used for this pur ...

What is the process for invoking a JavaScript function from the code-behind of an Asp.Net application?

Here is a sample of my JavaScript function : function NeedToExport() { alert('Time to export your data!'); } Additionally, in my ASP.NET code behind : Page.ClientScript.RegisterStartupScript(this.GetType(), "ExportKey", "NeedToExport();"); ...

Are you feeling lost when it comes to Javascript? How is it possible for a boolean function to function as a

Preparing for an upcoming interview, I'm diving back into the world of JavaScript. Recently, I came across an interesting blog post that mentioned: "The delete operator returns true if the delete was successful." The blog then provided an example ...

Utilizing a combination of Mongo, Mongoose, Multer, and FS for deleting images

Looking at the code snippet below:- var Image = mongoose.model("Image", imageSchema); //Assuming all the configuration of packages are done app.delete("/element/:id", function(req, res) { Image.findByIdAndRemove(req.params.id, function(err) { if(e ...

The Puppeteer software does not automatically shut down the browser once the task is complete

Currently, I have set up puppeteer on my Ubuntu server with Express and Node.js like so: var puppeteer = require('puppeteer'); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/&ap ...

Submitting a nested JSON object in an AJAX request

When it comes to passing nested JSON through AJAX, the format of the sample request should be like this: { 'user': { 'email': email, 'password': password } } login(){ var email=document.getElementById(& ...

Error message: Unspecified service injected

I am currently working with 2 separate javascript files for my project. One is being used as a controller, while the other serves as a service. However, when I attempt to inject the service into the controller and access its function, an error message pops ...

When deserializing a double type variable, JsonConvert encounters an 'invalid integer' exception

I encountered an issue while trying to deserialize a JSON string into an object. Newtonsoft.Json.JsonReaderException Input string '106.890907 is not a valid integer. Path 'data[0].loc.coordinates[0]', line 1, position 9413. This is the cod ...

Troubleshooting issue: Chrome bug causing JavaScript full height intro section to have incorrect padding and display issues

Trying to create a full-height intro section using basic JavaScript markup has been quite the challenge. Here's a more detailed explanation: I have a parent DIV element that is supposed to adjust to the full height of the viewport. Unfortunately, t ...

The VueJS component fails to load on the webpage

Here is my Vue.js component code that I am having trouble with. Despite its simplicity, it does not load correctly: Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: { msg: 'hello' ...

How to adjust cell alignment in Handsontable

Handsontable showcases cell alignment options in the align cell demo: Horizontal Left Center Right Justify Vertical Top Middle Bottom Displayed below is a screenshot: To retrieve data, utilize the following code snippet: $('#table-wrapper&ap ...

What is the best way to assign a value to process.env within an npm script?

After creating a new Vue app (using Vite) with npm init vue@latest and selecting Playwright for e2e tests, the configuration file was generated with a field for setting headless mode: const config: PlaywrightTestConfig = { // ... use: { // ... ...

What is the best method for caching inline SVG in web browsers?

Over the years, SVGs have remained popular due to their scalability. One key advantage of inline SVG is the ability to manipulate it with CSS and JS. Additionally, using the <use> tag allows for referencing the original element when repeating the sam ...

Getting the expanded row columns values in a RadGrid when using the onHierarchyExpanded event

Here is the code for my RadGrid: <telerik:RadGrid ID="ProductRanges_Grd" ShowHeaderWhenEmpty="true" runat="server" AutoGenerateColumns="false" Width="100%" Height="250px" ShowHeader="true" Visible="false" ...

Transferring JSON data to Google Sheets can result in unusual column formatting and all the information ending up in a

I have successfully established a connection to a secure JSON, but I am having trouble formatting the data into columns. The metadata includes nice "labels," but the column names are appearing strangely. For example, instead of Date: Streetname. I have at ...

Safari: The onbeforeunload event

Welcome! To experience the Leave | Stay confirmation box on your page, please make sure you are using Safari 10. I am currently facing an issue with getting the confirmation box to display properly across different browsers. To begin, please visit and l ...

Need to update React textarea with value that is currently set as readonly

In my React application, I have a textarea that is populated with a specific value. My goal is to allow this textarea to be updated and then submit the form in order to update the corresponding row in the database. <textarea id="description" className= ...

Using JQuery to switch classes and activate events

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <span class="fake_h">Too</span> </body> <script> $('.fake_h').click(function() { $(this).addClass( ...

Passport.socket.io cannot resolve the issue of a missing session

The Issue I am facing a problem with the failed connection to socket.io: No session found using passport.socketio.js and I am unable to identify the root cause. Despite checking similar posts, the configuration seems fine to me. However, it appears that ...