Tips on how to bring in .js that has brought in .json from an html file

English is not my first language, and I struggle with it, but I did my best.

I am attempting to include a js file that imports json from an html

.js

import menus from '../json/menus.json';

(function () {
  function parseMenu(ul, menu) {
    for (var i=0;i<menu.length;i++) {
      if(menu.sub == null) {
        menu.sort(function(a, b) {
          return a.id > b.id ? -1 : a.id > b.id ? 1 : 0;
        });
      }
      var li=$(ul).append('<li><a href="'+menu[i].link+'">'+menu[i].name+'</a></li>');
      if (menu[i].sub!=null) {
        var subul=$('<ul id="submenu'+menu[i].link+'"></ul>');
        $(li).append(subul);
        parseMenu($(subul), menu[i].sub);
      }
    }
  }
  var menu=$('#menu');
  parseMenu(menu, menus);
});

.json form

[ {
     {
     },
     {
     }
   },
   {
     {
     },
     {
     }
   },
   {
   }
]

I attempted the following

<script type="module" src="../js/left.js"></script>
<script type="module" src="../json/menu.json"></script>

in HTML

However, I encountered the error message: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json". Strict MIME type checking is enforced for module scripts per HTML spec. in .json

I managed to solve it.

First. Changed name of variable from JSON to menus

Second. Deleted

<script type="module" src="../js/left.mjs"></script>

Last. Changed

import JSON from '../json/menu.json';
to
import menus from '../json/menus.json' assert { type: "json" };

Answer №1

It appears that you might be attempting to utilize the .js file as a source in this section:

<script type="module" src="../json/menu.json"></script>

Currently, Chrome supports https://github.com/tc39/proposal-import-assertions, which allows you to specify to the browser that you are importing a JSON file:

import JSON from '../json/menu.json' assert { type: "json" };

Additionally, it is recommended not to use JSON as the variable name since it is a reserved built-in object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

Answer №3

const { variable: info } = await import("./info_data.json", { verification: { category: "information" } })

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

Using Javascript and JQuery to create an alert that pops up upon loading the page is not effective

I am having trouble making an alert show up when my website loads. The Javascript code is functional when directly included in the HTML, but once I move it to a separate file named script.js and link it, nothing happens. Can someone please help me identify ...

Troubleshoot and resolve the issue of a page scroll freeze bug occurring while scrolling through an overflowed

My webpage features a Hero section with 2 columns - the left column contains a gallery slider, and the right column consists of 2 text blocks. The challenge here is that the right column needs to be 100% of the screen height while scrolling. To achieve thi ...

"Enhance user experience with the React Popover feature from Material UI

Looking for help on creating a dynamic color palette with a hover feature for the PaletteIcon. The issue I'm facing is that when I try to select a color, the palette disappears. Is there a specific property I should add to the React component or anoth ...

Receiving reliable information from an API in my Node server without experiencing any disruptions

A node server is being utilized to retrieve trades data from Binance. With more than a thousand pairs for which trades need to be fetched, the function takes some time to execute completely. To ensure that new data keeps coming in while the server is live ...

Steps to retrieve the array values for a specified descendant in a JSON data structure

{ "hasLoadMore": true, "groups": [ { "order": 0, "title": "string", "total": 0, "dateFormat": "string", "messages": [ { "commsId": 0, "commsDirectionCode": "string", "commsReasonCR ...

How can I make sure a Post method finishes executing before returning the result of a Get method in Express.js?

I am currently utilizing the Ionic framework and Express to facilitate communication between my application, a server API, and a JavaScript game. The game transmits information to the API through XMLHttpRequest and post requests, while my application retri ...

What is the best way to arrange an array of objects based on a specific attribute?

Ordering object based on value: test": [{ "order_number": 3, }, { "order_number": 1, }] Is there a way to arrange this so that the object with order_number 1 appears first in the array? ...

Angular8: Stay Updated with Real-Time Data Refreshment

I've implemented code in my app.component to retrieve all users. I'm facing an issue where if I have two windows open and perform any CRUD actions, the second window displays outdated data. To address this, I am attempting to refresh the page ev ...

In Next.js, the 404 error page is displayed using getInitialProps

Currently, I am learning how to redirect users in getInitialProps by following a helpful example. Here is the link to the example I am referring to However, I encountered an issue where when I try to return a 404 error using the code snippet provided, in ...

jquery.event.drag - Execute code for each increment of X pixels dragged

Currently, I am utilizing jquery.event.drag.js for a project I am developing. My goal is to execute a script after every interval of X pixels dragged along the X axis. Below is a snippet of the code I have implemented. $('body').drag(function( e ...

Generate a high-resolution image using PhaserJS

I've been experimenting with creating graphics using PhaserJS and now I'm looking for a way to export them as high-resolution images or, even better, as vector-based graphics. Here's an example of the code I've been working on: var con ...

Can someone provide a list of events for the .on function in Vanilla NodeJS?

Currently experimenting with NodeJS by testing basic backend functionalities like sending various HTTP requests from my index.html file to the server.js file. I plan to delve into Express soon. I've noticed a lack of documentation on NodeJS 'eve ...

If I do not specify whether a variable is declared using var or let, what will be its scope?

As someone who is new to JavaScript, please forgive me if my question is not entirely valid. What will be the scope and type (var/let) of a variable if I do not specifically define it as var or let? For example: function f1(){ a="Sample" console.log(" ...

Arrange a QJsonArray in a particular order

Let's say there is a function with the following signature: bool sortJson(QJsonArray &); The purpose of this function is to sort the QJsonArray and return true only if all members are of type double. One way to achieve this is by creating an aux ...

Determining with jQuery if the right element has been successfully "dropped"

Imagine having 10 different draggable boxes and 2 droppable areas. You need to correctly match 5 boxes with droppable area 1 and the other 5 with droppable area 2. If a box intended for droppable area 1 is mistakenly dropped into area 2, it should not wor ...

Tips for creating a textarea element that resembles regular text format

I am working on creating an HTML list that allows users to edit items directly on the page and navigate through them using familiar keystrokes and features found in word processing applications. I envision something similar to the functionality of To achi ...

A PHP code snippet that encodes HTML content within JSON format

I recently developed a PHP script to check the response of an external system that returns a JSON string. However, I encountered an issue where there is HTML content embedded within the JSON data. I attempted to set a header but unfortunately, it did not r ...

How jQuery stops the submission of a form

Sample HTML Code <p><select name="status" class="form-control" id="showThisItem"> <option value=""> Select Status </option> <option value="Paid"> Paid </option> <option value="Unpa ...

Deciphering and Organizing JSON Data from Twitter Streams

I'm having difficulties with the formatting and encoding of the Twitter stream collected by a Python script I wrote. The output is displaying as shown below: {"created_at":"Wed May 07 20:53:05 +0000 2014", "id":46414592 ...

Ways to adjust various json files

I'm facing a task where I have a directory containing 100 json files, and my goal is to insert [ at the start and ] at the end of each file. The current structure of the files is as follows: { item } But what I need to achieve is this format: [{ i ...