Unexpected token ILLEGAL .. somewhere

2019-07-19 05:31发布

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'm tearing my hair out; I cannot get the (compiled equivalent) function to run, always getting the illegal token error. I've checked for rogue, invisible characters and there's nothing besides CR/LFs in there.

1条回答
Emotional °昔
2楼-- · 2019-07-19 05:58

You're calling JSON.parse on an array, which apparently qualifies as a syntax error instead of a normal exception due to the way browsers implement it. You're essentially doing this:

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

Which is the same as:

JSON.parse('[object Object]')

Which is illegal JSON, hence the error.

查看更多
登录 后发表回答