简体   繁体   中英

JSON Parse: Uncaught SyntaxError: Unexpected token e

I am trying to parse a JSON string. This is the contents of the string:

[[ new Date(2016, 2, 11), 439 ],[ new Date(2016, 2, 10), 1110 ],[ new Date(2016, 2, 9), 9 ],[ new Date(2016, 2, 8), 2 ]]

This is the code

var data = JSON.parse(str);

This is the error

Uncaught SyntaxError: Unexpected token e

How can I prepare this string to be parsed by JSON.parse() ?

You need to replace each instance of new Date(2016, 2, 11) with a valid JSON data type.

You could express a date with, for example, a string containing a ISO 8601 data or a number representing the seconds since the epoch.

我用以下方法解决了这个问题:

eval( "data = " + str );

In JavaScript, construct it something like this ( http://www.w3schools.com/json/json_syntax.asp )...

// Bear in mind that month 2 = March in JavaScript!
var dte1 = new Date(2016, 2, 11);
var dte2 = new Date(2016, 2, 10);
var dte3 = new Date(2016, 2, 9);
var dte4 = new Date(2016, 2, 8);

var str = '[ ';
str += '{ "d": "' + dte1.toJSON() + '", "n": 439 }, ';
str += '{ "d": "' + dte2.toJSON() + '", "n": 1110 }, ';
str += '{ "d": "' + dte3.toJSON() + '", "n": 9 }, ';
str += '{ "d": "' + dte4.toJSON() + '", "n": 2 } ]';

var data = JSON.parse(str);

alert("Date: " + data[0].d);
alert("Amount: " + data[0].n);

I've constructed this as an array of objects with properties d and n, to allow you to access the date and the number of each object in the array. You should call these something more meaningful to your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM