Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught SyntaxError: Unexpected token with JSON.parse

what causes this error on the third line?

var products = [{    "name": "Pizza",    "price": "10",    "quantity": "7"  }, {    "name": "Cerveja",    "price": "12",    "quantity": "5"  }, {    "name": "Hamburguer",    "price": "10",    "quantity": "2"  }, {    "name": "Fraldas",    "price": "6",    "quantity": "2"  }];  console.log(products);  var b = JSON.parse(products); //unexpected token o

Open console to view error

like image 505
coiso Avatar asked Jan 21 '13 03:01

coiso


1 Answers

products is an object. (creating from an object literal)

JSON.parse() is used to convert a string containing JSON notation into a Javascript object.

Your code turns the object into a string (by calling .toString()) in order to try to parse it as JSON text.
The default .toString() returns "[object Object]", which is not valid JSON; hence the error.

like image 55
SLaks Avatar answered Sep 20 '22 11:09

SLaks