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); 
8
  • 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. Commented Jul 20, 2020 at 11:35
  • Either request it via AJAX, or use JSONP. Commented Jul 20, 2020 at 11:37
  • 2
    fetch('levels.json').then(r => r.json()).then(data => { /* do sth with data */ });, also stackoverflow.com/questions/14220321/… Commented Jul 20, 2020 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 Commented Jul 20, 2020 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 Commented Jul 20, 2020 at 11:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.