0

what's this in chrome console " Uncaught SyntaxError: Unexpected token ':' "

here is json file in root of application:

  <script src="levels.json"></script>

and this is my json file content :

{
    "levels": [
        [22, 22],
        [33, 25]
    ]

}

and my javascript code :

  let data = JSON.parse(levels)
        console.log(data);


keyvan
  • 1
  • 4
  • 6
    You can't load json files using a script tag. The error is fired, because the loaded file is tried to parse to JavaScript. `{...}` is parsed as a code block, the quoted property name is just an expression, and finally the lonely colon causes the error. – Teemu Jul 20 '20 at 11:35
  • Either request it via AJAX, or use [JSONP](https://en.wikipedia.org/wiki/JSONP). – CBroe Jul 20 '20 at 11:37
  • help me please @Teemu – keyvan Jul 20 '20 at 11:38
  • 2
    `fetch('levels.json').then(r => r.json()).then(data => { /* do sth with data */ });`, also https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call –  Jul 20 '20 at 11:40
  • how is that @CBroe i dont have ajax request im testing in local mode – keyvan Jul 20 '20 at 11:40
  • 1
    Local as in `file:///...` in your address bar? Then it won't work at all; you need a server. Or you change the file to levels.js and use `const data = { ... }`, in that case any code further down can simply use `data` –  Jul 20 '20 at 11:41
  • 2
    You could assign all that json to a variable in a js file to get it going temporarily. Then it is valid javascript and doesn't need parsing – charlietfl Jul 20 '20 at 11:42
  • @ChrisG The linked post is outdated, AJAX can't access local files in any modern browser anymore, unless you are configuring the browser settings to do so, but that seems not to be the subject of the proposed dup. – Teemu Jul 20 '20 at 11:56

1 Answers1

1

You could load a "JSON" file via script tag but for that, your "JSON"-File must be written in JS syntax because the browser will try to parse your JSON in script tag.

JSON:

{"name":"John", "age":31, "city":"New York"}

"JSON" in JS syntax

const data = {"name":"John", "age":31, "city":"New York"}

After loading your "JSON" you have a global variable named data.

alexP
  • 3,672
  • 7
  • 27
  • 36
  • This question is a duplicate: https://stackoverflow.com/questions/7346563/loading-local-json-file –  Jul 20 '20 at 11:46