What is the easiest way to access my JSON data within my script?

My file structure looks like this

app/
  index.html
  script.js
  data.json

Does that make sense? Now, I want to randomly select an object from my JSON data and display it to the user each time the document loads. However, I'm facing an issue with efficiently accessing the data from my data.json. Using XMLHttpRequest() or the fetch API seems like overkill for such a simple task. I mean, you don't need to send an HTTP request to link your CSS and HTML files, right?

I've tried linking my data using

<script id="data" src="./data.json" type="application/json"></script>
but it didn't work as expected. A workaround I found was renaming data.json to data.js, adding a var data = prefix to the JSON data, and importing it into index.html. This method feels hacky and not optimal.

It seems like there may be some issues related to CORS/Same-origin that I don't fully understand. Can someone provide a detailed explanation on why an HTTP request is necessary to access a local file? Why can't we simply link our JSON data like we do with HTML, CSS, and JS files using link/script tags?

Answer №1

Here are three different strategies that can be employed:

1) Retrieve the data from a .json file using Fetch or XHR

The standard method for a web document to fetch a .json file from the server is through the use of the Fetch API or XHR.

fetch('/app/data.json')
  .then(response => response.json())
  .then(json => console.log(json));

2) Opt for a .js file instead of a .json file

One alternative approach is to upload a .js file to the server rather than a .json file. For instance, consider transforming your JSON data like so:

{"Name" : "Data", "Section 1" : {"A" : "a", "B" : "b"}, "Section 2" : ["C", "D"]}

Your JS file would then appear as follows:

let myJSONData = '{"Name" : "Data", "Section 1" : {"A" : "a", "B" : "b"}, "Section 2" : ["C", "D"]}';

This JavaScript file can be linked in your document with:

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

3) Integrate the .json file into the document (using <object> or <iframe>)

An additional method involves embedding the .json file within the document utilizing <object> or <iframe>:


Utilizing HTML5 <embed>

<embed> seems to have restricted access to its contentDocument, though it's unclear why.


Utilizing HTML5 <object>

HTML:

<object data="/app/data.json" style="display: none"></object>

JS:

<script>
let myObject = document.getElementsByTagName('object')[0];

const getJSONFromObject = () => {
  console.log(myObject.contentDocument.body.textContent);
}

myObject.addEventListener('load', getJSONFromObject);
</script>

Utilizing HTML5 <iframe>

HTML:

<iframe src="/app/data.json" style="display: none"></iframe>

JS:

<script>
let myIframe = document.getElementsByTagName('iframe')[0];

const getJSONFromIframe = () => {
  console.log(myIframe.contentDocument.body.textContent);
}

myIframe.addEventListener('load', getJSONFromIframe);
</script>

In terms of personal preference, the ranking of these approaches would be:

  1. Fetch the .json file
  2. XHR the .json file
  3. Utilize a .js file rather than a .json file
  4. Embed the .json in the document via <object>

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

configuration of file types

While using Ipage as my web host, I encountered an issue with an Html document on my server. The problem arose because a json.z file was being read by the browser as "text/html" instead of "application/json; charset=UTF-8", as confirmed in fiddler. Is the ...

Importing text data from a text file in Java or jQuery without the need for a web server

I've attempted to utilize both the jQuery.Get() and $.Get() methods for this task, but they don't seem to be working as expected. <head> <script type="text/javascript" src="jquery-2.1.3.min.js" > </script> <script lang ...

The validation of the JSON schema reveals no discrepancies

I am facing an issue with Ajv version 6.10.2 while trying to validate a Json schema that is split into two separate files. Despite using incorrect test json data, I am not receiving any error messages during the validation process. Here are the two parts ...

Having trouble rendering JSON encoded data in a JqPlot Chart within a PHP script

I've spent the past few days scouring through Stack Overflow and various other websites, but I haven't been able to find a solution to my specific issue. Even the book 'Create Web Charts with JqPlot' by Fabio Nelli didn't provide t ...

"Auth.currentSession is indicating that there is no user currently logged in

I am currently working on a basic React app with authentication using aws-amplify. My user pool is set up in Cognito and I can successfully redirect the user to the hosted UI for login. However, when trying to retrieve the current session, I am receiving a ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

Retrieving table information using javascript

My goal is to retrieve information from the <td> elements within the following HTML table: <table class="datadisplaytable" summary="This table lists the scheduled meeting times and assigned instructors for this class.."> <caption class="cap ...

Can you explain the purpose of CLOUDINARY_DEFAULT_URL and CLOUDINARY_DEFAULT_PUBLICID to me?

Need help with my user sign up page Here is my .env file This is my signup controller code: const User = require('../model/User'); const bcrypt = require('bcrypt'); const { uploadToCloudinary } = require('../utils/cloudinary&apos ...

Having trouble retrieving data from an API URL in JSON format using the Flutter framework

Attempting to retrieve API JSON data such as id, username, photo, etc., I encountered a problem. When using jsonplaceholder, everything works fine; however, when utilizing my own API, no data is returned. Below is the Flutter code I'm using: import ...

Sending Svelte data to Javascript with an onclick event

In my Svelte store, I have an ASCII-Logo that I want to integrate into a button spanning two symbols ("-."). However, I do not want to split the ASCII into separate parts and just insert the button between them on my +page.svelte. Currently, I h ...

Issue with specific route causing server to throw 500 error

Recently, I have been working on a small school project that involves creating our own API and connecting it to an Angular front end. While following some tutorials, I encountered an issue where my application started throwing internal server error 500 af ...

Access to PHP script (IF) unattainable following a POST occurrence

I'm completely new at this. I am attempting to create a contact form using HTML5 and PHP mail function, but I am facing an issue with my form action pointing to contacto.php. After submitting the form, it seems to be skipping over the IF condition wi ...

Tips for eliminating corner indexes from a 2D array?

Exploring forward ray tracing algorithm using Three.js. I have developed a sample using a 2D array where the Spotlight's location is parsed, but not directly involved. To create lines of sight, I set: startPoint = position of SpotLight endPoint = ...

JavaScript - The function will not execute any code inside its body

When I try to call my constructor function, it stops at the function definition in the debugger and never reaches the actual function body. Is there a common reason for this issue that I might be missing? Here is an example of the code: myconstructor.js ...

Retrieve filled out form fields in ServiceM8

Is there a way to retrieve completed form field data in ServiceM8, including uploaded images? I've looked through the API reference but couldn't find any information on how to access them. Can someone share an example or provide documentation on ...

Switching the delimiter for JSON queries using Json.net

Currently, I am utilizing the Newtonsoft Json library to query a JSON string by employing the SelectToken method, which utilizes "." as a delimiter to navigate through the JSON hierarchy in accordance with the documentation provided here: https://www.newt ...

Fixing the Jquery animation glitch triggered by mouseover and mouseout

In my project, I have implemented a small mouseover and mouseout functionality. The challenge I am facing is that I need to keep the mouseout function using animate() instead of css() for specific reasons. The issue arises when I quickly do a mouseover fo ...

Adjusting the height of an element as you scroll will activate the scroll event

One issue I'm facing is with adding a class to my header. The goal is to reduce the height of the top part of the header when the user scrolls down and then remove the class when they scroll back up. While this functionality is working, there is an un ...

Exporting a table in Quasar to JSON format

Currently, my focus is on studying quasars and I am seeking guidance on how to export a table to JSON format. I have imported data in JSON format and now wish to generate output in JSON as well. I have been using the JSON.stringify method to extract data ...

Tips for preloading a script in nextjs

I'm having trouble incorporating a script into my website. The issue is that the script doesn't load properly the first time the page loads, but after a few refreshes, it works and the responsible iFrame shows up. I've attempted several di ...