Unexpected token is ILLEGAL .. somewhere

addToBasket = (id, qty) -> if $.cookie('basket')? # Basket exists basket = $.parseJSON($.cookie('basket')) basket.push( { 'id': id, 'qty': qty } ) $.cookie('basket', JSON.stringify(basket)) else # Basket doesn't exist alert 'Creating basket' basket = JSON.parse([{'id': id, 'qty': qty}]) $.cookie('basket', JSON.stringify(basket)) 

I pull my hair out; I cannot run the function (compiled equivalent), always getting an illegal token error. I checked for rogue, invisible characters and there is nothing but CR / LFs there.

+2
coffeescript
source share
1 answer

You call JSON.parse into an array, which apparently qualifies as a syntax error instead of the usual exception due to the way browsers implement it. You essentially do this:

 JSON.parse([{id: 123}].toString()) 

This is the same as:

 JSON.parse('[object Object]') 

This is illegal JSON, hence the error.

+1
source share

All Articles