0

I am new to javascript / html and have some problems to understand the import / module functionality. I need to load a json file into javascript.

The best way I could find is via import, like:

  import myJason from './dummy.json' assert {type: 'json'};

When trying it, I am getting following error:

  Cannot use import statement outside a module

So I placed it into a module (tried header and body). But I am not able to access the module functions.

Google could not help me, could please somebody explain how to do it properly.

Note: HTML and JSON files are local files (not accessed via Webserver)

Here is the (reduced) code:

    <html lang="en">
        <head>
            <script type="module">
                import myJason from './dummy.json' assert {type: 'json'};
                function dummy(){
                    //evaluate JSON
                    return result();
                }
                window.dummy = dummy;
                export{dummy}

            </script>
        </head>
        <body>


            <script>
                // tried (and other things)
                //   dummy();
                //  window.dummy();
            </script>
        </body>
    </html>





  
JustMe
  • 366
  • 1
  • 4
  • 14
  • maybe look into loading JSON data in via "Ajax" - also, using `import` is part of something called Es6 with javascript which requires a compiler, you will need to use es5 syntax instead – alilland May 28 '22 at 07:19

1 Answers1

1

Try using XML HttpRequest

var xhttp = new XMLHttpRequest();

function dummy(){
    if (this.readyState == 4 && this.status == 200) {
       return JSON.parse(xhttp.responseText)
    }
}

xhttp.onreadystatechange = dummy
xhttp.open("GET", "/dummy.json", true);
xhttp.send();

or even better the fetch api check that here

net-js
  • 119
  • 1
  • 8
  • Sorry, I forgot to mention that the HTML and JSON Files are local files (not accessed via Webserver). It seems that the provided solution do not work locally. – JustMe May 28 '22 at 07:58
  • then check this [local file access](https://stackoverflow.com/questions/371875/local-file-access-with-javascript) – net-js May 28 '22 at 08:01