0

I am trying to use fetch to import a local json file in JavaScript but I keep getting the error for the 2nd line of the json file:

Uncaught SyntaxError: Unexpected token ":"

Here is my json file:

{
    "items": [
        {
            "key 1": "abc",
            "key 2": {
                "xyz": [
                    {
                        "name": "abc",
                        "version": "1.0.0",
                    },
                    ...                
                ]
            },
            "key 3": {
                "...": [
                    {
                        ...
                    },
                    ...                
                ]
            },
        },
        ...
    ]
}

I've used an online json validator, and confirmed that my json.

Here is my JavaScript code:

<script src="file.json">
    fetch("./file.json")
        .then(res => res.json())
        .then(data => console.log(data))
        .catch(err => console.log(err))
</script>
worrier
  • 81
  • 1
  • 7
  • if the JSON validator validates the JSON, then the only possibility is that you are sending something from the server that is not the exact contents of the JSON file - show the code for the server - check what the browser receives using your browser developer tools – Bravo Mar 30 '22 at 03:01
  • @Bravo No, the JSON being valid or invalid isn’t the issue. The issue here is that `src="file.json"` will cause the `fetch` code to be completely ignored. Instead the JSON itself will be loaded and interpreted as JavaScript. But `{ "items": [`…`] }` isn’t a valid JavaScript script. The first step, therefore, would be to remove the `src` attribute. – Sebastian Simon Mar 30 '22 at 03:03
  • ahhh you are correct @SebastianSimon - I did not even notice the src attribute - I'm old, and my eyes are bent and my back is blind :p – Bravo Mar 30 '22 at 03:07
  • Hey Bravo and @SebastianSimon, thanks for the quick replies. Removing the src attribute gave the error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, chrome-untrusted, https – worrier Mar 30 '22 at 03:09
  • @worrier Good, that’s one step closer. Are you trying to do this from a `file:` protocol? That’s not supported. You can try hosting a `localhost` server instead. – Sebastian Simon Mar 30 '22 at 03:11
  • @SebastianSimon is there no way to directly import json files using JavaScript? – worrier Mar 30 '22 at 03:14
  • i solved the issue by converting the json file into a js file instead – worrier Mar 30 '22 at 03:43

0 Answers0