How can I load a .json file into JavaScript without inserting it directly into the code?

Currently, I am dealing with a lengthy JSON snippet that resembles the following:

{
  "section: [
   [stuff]
  ]
}

To incorporate this into my JavaScript code, I currently use the following approach:

var obj = {

  // {All the stuff from above}
}

My goal is to store it in a JSON file that can be locally imported into a JS script and function similarly to this:

var obj = "path/file.json";

and have it perform in the same manner.

Answer №1

Utilize AJAX along with fetch to accomplish this task.

const jsonFilePath = "./path/file.json";
fetch(jsonFilePath)
  .then(res => res.json())
  .then(json => {
    console.log(json.section);
  });

Keep in mind: This method only functions with a server. If you are utilizing the file:/// protocol, consider switching to a regular server. For instance, if you have Python installed, you can run the following command in your directory: python3 -m http.server.

An alternative (though not recommended) is creating another JavaScript file for your JSON data. Inside it, define the data as follows:

var obj = {
  "section": {
    ...
  }
}

Then, link this file in your HTML using a script tag before your main script:

<script src="./json-data.js"></script>
<script src="./my-script.js"></script>

In your my-script.js file:

console.log(obj.section); // {...}

Answer №2

Utilizing async with fetch enables seamless usage without the need for callbacks.

For more comprehensive information, please refer to: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

async function fetchAndParseJSON() {
  var data = await fetch("/path/to/data.json");
  var jsonData = await data.json();
  // manipulate JSON object as needed
}
fetchAndParseJSON();

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

The Google geocoding API is experiencing issues on Android devices, but is functioning properly on systems using Ripple in Apache Cordova

After developing a test app for finding weather based on zip/pin codes, I encountered an issue with the json resultset not displaying on android mobiles while using the google geocoding api. Interestingly, it worked perfectly on my system when tested with ...

Chaining updateMany() calls in MongoDB while ensuring synchronous response handling

I have encountered an issue while attempting to send 3 separate updateMany requests within a get request, each using a different query. While the first two requests work perfectly, the third updateMany request only functions as expected after refreshing th ...

Unable to fetch data using getJSON method

objecten.js var objectData = [ { image: 'gallery/objecten/bear.jpg', thumb: 'gallery/objecten/bear.jpg', title: 'my first image', description: 'Lorem ipsum caption&apos ...

Encountered issue while jasmine mocking angular $http - Error: describe function does not support a done parameter

I am currently working with an angular factory that looks like this: .factory('widgetFactory', ['$http', function($http){ function getWidgets(){ return $http.get('http://example.com/api/widgets/') .then(function(re ...

Deciphering a hierarchical JSON array without identifiers in C#

Here is a nested JSON array structure: [ [ [ [1234.5 ,9876,5], [1234.5 ,9876,5] ], [ [1234.5 ,9876,5], [1234.5 ,9876,5] ] ], [ [ [1234.5 ,9876, ...

create a JavaScript array variable for posting items

My goal is to use this javascript to make four posts for the 'var msg' array. However, it currently posts 'encodeURIComponent(msg[i])' four times instead. How can I resolve this issue? var msg = ['one', 'two& ...

The server's reply can be either an empty object or an error stating "Unexpected token < in JSON at position 0" in Node

While experimenting with a fake JSON file in a single-page app, I keep encountering the error Unexpected token < in JSON at position 0, or receiving an empty object when using JSON.stringify() on my promise return. This issue has been troubling me for t ...

I am looking to utilize the data from a POST request to dynamically update the DOM through a script.js file. How can

After sending a post request, I am looking to update my database and then use an array to dynamically update the HTML content. However, I am struggling with how to pass this data to my script.js file. Here is my progress so far: SERVER let expenseAmo ...

Sending a JavaScript string to a PHP script from a Chrome extension content script

I am currently developing a chrome extension that is designed to extract text data from specific websites when I visit them, and then store this data in a SQL database. The JavaScript code for data extraction is functioning correctly and is able to capture ...

Synchronizing the DOM with the Database in a React Component/View: A Step-by-Step

I recently developed a list component in React, but I'm facing two significant challenges. Although the item gets removed from the database, the change is only visible after refreshing the page. You might have noticed that the list number or ID colu ...

Modify the appearance of an element within an array upon selection by comparing it with a separate array

In my code, there is an array called tagList that contains a list of objects. When one of these objects is clicked on, it gets added to another array named selectedTags. var selectedTags = []; export default class RegisterTags extends Component { con ...

Executing ajax requests in MVC 5 using Webgrid

The objective: To dynamically update the webgrid without reloading the page using ajax when navigating to the next page. My current setup : public ActionResult Index() { var users = (from a in _context.Audit select new ...

Continuing deserialization process even after exception is caught

Here is a sample of the json data I'm working with: [ { firstKey : "value1", secondKey : "value2" }, { firstKey : "value3", secondKey : "value4" } ] My goal is to convert the api response (json) into ...

What is the best way to create an Office Script autofill feature that automatically fills to the last row in Excel?

Having trouble setting up an Excel script to autofill a column only down to the final row of data, without extending further. Each table I use this script on has a different number of rows, so hardcoding the row range is not helpful. Is there a way to make ...

You cannot nest a map function within another map function in React

Having some trouble applying the map function in HTML using React. Below is the code snippet: response = [ data : { name: 'john', title: 'john doe', images: { slider: { desktop: 'link1', mo ...

How can I convert the JSON array response from the API, which is of type string, back into an array?

Is there a way to change a string type array back into an array? var arr = '[ "abc", "def"]'; console.log(typeof arr) ==> String How can I convert it back into an array format? I'm receiving this string-formatted array from an API r ...

Using Ajax and Session Variables for a Worksafe Filter to selectively hide images

Creating a photography portfolio with some images containing nudity prompts the need to hide them by default until the user chooses to reveal them by clicking a "Toggle Worksafe Mode" button. To prevent "confirm form resubmission" errors when users naviga ...

Grab the source attribute of the <img> tag (identified by class) across numerous HTML pages

Here is an example: A website has the URL , where xxxx represents an integer between 1 and 1935. On each page, there may be an <img class="thumbnail" src="Images\Robots\{robotname}.png">. However, not all pages have th ...

Leveraging the $dirty property in AngularJS to determine if any changes have been made to a form

Recently, I've been attempting to determine if my form is being edited by monitoring certain fields. I've come across $dirty as a potential solution for this task, but unfortunately, I'm struggling to identify what exactly I'm overlooki ...

Uploading files in NodeJS using the multer library

I am attempting to upload a file to a specific directory on the disk using the multer library. As I analyze the code, it seems that when a request is made, the file is taken from it and saved separately from the rest of the request. Is there a way to acces ...