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

Trigger an event on an element upon first click, with the condition that the event will only fire again if a different element is clicked

Imagine having 5 span elements, each with an event listener like ` $('.option1').on("click", function(){ option1() }) The event for option 1 is also the default event that occurs on page load. So if no other options are clicked, you won&apo ...

Interpolating strings in a graphQL query

Exploring the world of Gatsby and its graphQL query system for asset retrieval is a fascinating journey. I have successfully implemented a component called Image that fetches and displays images. However, I am facing a challenge in customizing the name of ...

When attempting to use dynamic imports with `react-icons`, NextJS will import all necessary components and dependencies

My current task involves incorporating an Icon from the react-icons package into my project. However, when I attempt to do so using an import statement, the resulting bundle size looks like this: Route (pages) Size First Lo ...

Preventing memory leaks by harnessing the power of Node Streams and promises

I am trying to wrap node streams in an async function, but I'm concerned about potential memory leaks in the following code. Will readStream and result be properly garbage collected after the promise is resolved or rejected? If not, what steps can I t ...

Submit a POST request using CoffeeScript to get a string from the returned object

I am encountering a small issue. Whenever I execute myVar = $.post('/check_2/', JSON.stringify({"newname": window.NEWNAME,}), callback, 'json') The variable 'myVar' holds an object. When I use console.log myVar, the output i ...

Error in Node.js: [Error: Query parameter should not be empty]

I've been recently focusing on a project that involves sending the required name to my profile.js file using a POST request. However, whenever I try to access console.log(req.body.bookName) (as the data being sent is named bookName), it shows an error ...

My React setup is causing some problems that I need to address

React is not my strong suit, but I need to test a React application. The issue arises when attempting to run the server using gulp nodemon, resulting in numerous errors. It seems that the application is built on an outdated version of React and some libra ...

Finding the index of an element in an array using the filter method in Angular JavaScript

As I was working with an array of pages in a book, I wanted to find the index of a specific page that had been identified using filter. While my current function gets the job done, I can't help but wonder if there's a way to combine indexOf or fi ...

Is there a way to invoke an Angular2 function from within a Google Map infowindow?

I am currently working on integrating Google Maps using javascript in a project, and I'm facing a challenge. I want to call an Angular2 function inside an infowindow as shown in the code snippet below. Pay attention to the infoContent variable that co ...

The functionality of the Bootstrap carousel for moving to the next and previous images is malfunctioning, as it only

The carousel on my website is not functioning properly. It only displays the first image and does not slide to the next pictures as it should. Here is the code snippet for the carousel: <body> </nav> <div id="carousel1" class="carousel slid ...

Deselect the checkbox that was initially selected when an alternative checkbox option has been chosen

I am trying to implement a feature where there are 2 groups of checkbox options on the same page. Below is the code snippet: <div class="col-xs-12"> <label class="checkbox-inline"> <input type="checkbox" th:field="*{borrowerRace1}" th:val ...

Get JSON or partial HTML responses from ASP.NET MVC controller actions

Is there a recommended method for creating controller actions that can return either JSON or partial HTML based on a specified parameter? I'm looking for the optimal way to asynchronously retrieve the results in an MVC page. ...

When submitting a form in HTML, ensure that the input checkbox returns 'On' instead of 'True'

My MVC3 app is using Project Awesome from http://awesome.codeplex.com/, but I'm encountering a strange issue with checkboxes. Inside a Modal popup, I have the following simple Html code: <input type="checkbox" class="check-box" name="IsDeleted"> ...

Tips for transferring a JavaScript object to a Node.js server

I must admit, I am positive that the solution to my issue is incredibly simple yet it has been evading me for more than a week now and causing me endless frustration. My current project involves creating a web app for quoting purposes within my workplace, ...

Tips on elevating a dragged div above all other elements when utilizing two scrollbars

Currently, I have two horizontal scrollers where I need to drag a div from the upper scroller to the lower scroller. While this functionality is working properly, there is an issue with the dragged div getting lost under the borders of the scroller during ...

Tips on how to increase and update the index value by 2 within an ngFor loop while maintaining a fixed format

I have a specific template layout that displays only two items in each row as shown below. I want to use the ngFor directive to iterate through them: <div class="row" *ngFor="let item of cityCodes; let i = index"> <div class="col-6" (click)= ...

Calculate the sum of the products when multiplying two values from every array of objects, using Reactjs/Javascript

I'm currently developing an eCommerce application and need to calculate the total price of items that users have ordered. I have an array named 'orders' which contains all the ordered items, each item has two keys - payablePrice and purchase ...

What are some ways to streamline this D3 script?

My CSV data displays pass rates by organisation for different years: org,org_cat,2004_passed,2004_total,2005_passed,2005_total,2006_passed,2006_total GSK,industry,35,100,45,100,55,100 I am using D3 and aiming to create a dictionary of organisations struc ...

Changing HTML dynamically does not trigger the ng-click event within ng-bind-html

I have developed a custom directive that can display messages along with rendering HTML content that may contain Angular attributes like buttons, anchor tags with ng-click attribute, and more. index.html: <ir-error-panel status="status"></ir-err ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...