Reputation: 113
I am not an English-speaking citizen, I am not good at English but I did best.
I am trying to import a js file that imported json from html
.js
import JSON from '../json/menu.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, JSON);
});
.json form
[ {
{
},
{
}
},
{
{
},
{
}
},
{
}
]
I tried like
<script type="module" src="../js/left.js"></script>
<script type="module" src="../json/menu.json"></script>
in html
But I get the following error 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 solved it.
First. Changed name of variable. 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" };
Upvotes: 9
Views: 14360
Reputation: 436
assert
is deprecated. Use with
instead.
import JSON from '../json/menu.json' with { type: "json" };
Upvotes: 4
Reputation: 11
const { default: jsonData } = await import("./data.json", { assert: { type: "json" } })
Upvotes: 1
Reputation: 672
My guess is you are actually trying to use the .js
as src in this part:
<script type="module" src="../json/menu.json"></script>
Chrome currently supports https://github.com/tc39/proposal-import-assertions. This allows you to tell the browser that you are importing a json file:
import JSON from '../json/menu.json' assert { type: "json" };
By the way you shouldn't use JSON
as the name of variable because it is a built-in object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
Upvotes: 26