JSON.parse: unexpected non-whitespace character af

2019-03-30 04:11发布

I get this error when debugging my highcharts javascript code via Firebug. Here are the relevant lines of code:

var valpair = [parseInt(items[0]),cumulative];
rain_series.data.push(JSON.parse(valpair)); 

items[0] is just "1234567", and if I add console.log(valpair) to my code, I get this output: [1234567, 0] which seems to be valid JSON. Nevertheless, I'm stuck on my error (I searched for a solution, but didn't find one for my case).
Anyone here who knows what I'm doing wrong?

1条回答
\"骚年 ilove
2楼-- · 2019-03-30 04:31

It's because you're using JSON.parse to try to parse an array, which is not going to work. Just get rid of the JSON.parse, and this should work as expected.

When you call JSON.parse on something that's not a string, it's going to coerce it to a string by calling .toString() on it. If valpair = [1234567, 0], then valpair.toString() is going to yield 123457,0 (this is probably dependent on the JS engine: I get 123457,0 in Chrome). This is invalid JSON: the "unexpected non-whitespace character" is the comma.

查看更多
登录 后发表回答