GladH
GladH

Reputation: 25

Retrieving data from JSON file in JS getting an error

Im getting a Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

var mydata = JSON.parse("file.json");
console.log(myJSON)

Below is an example of the data in the JSON file.

[[1,1,0,1,1,0,0,0,1,1,1,1,1,1],
[1,0,0,1,1,0,0,0,1,1,1,1,1,0],
[1,0,0,1,1,0,1,1,1,1,1,1,1,1],
[1,0,0,1,1,0,0,0,1,1,1,1,1,0], .... etc]

How can I retrieve the data from this JSON file in JS?

Is it not possible to write a JSON like this?

When I open the file in the browser, it looks like a neat JSON array?

browser JSON file

Upvotes: 0

Views: 73

Answers (1)

Vyacheslav Palamar
Vyacheslav Palamar

Reputation: 507

JSON.parse expects an actual JSON string instead of the file name, e.g. JSON.parse('{ "a": "b" }'). If you want to do it inside Node.js, you can use fs module to read file and parse it. In browser, you need to use file input to read the file first.

Upvotes: 1

Related Questions