json.parse unexpected token error
I'm trying to parse string to json object but i always get the same error SyntaxError: unexpected token '
var data = ('{' + fields.productName.toString() + ":" + parseInt(fields.quantity.toString()) + '}' );
I tried few variation of this but nothing works.
Best way to avoid issues :
var data = {};
data[fields.productName.toString()] = parseInt(fields.quantity.toString());
PS Leverage the beauty of JS objects, Do not re-invent the wheel by constructing object using strings :)
I don't think you need that, just do this:
var fields = {productName: 'hello', quantity: 1};
var data = {};
data[fields.productName.toString()] = parseInt(fields.quantity.toString());
console.log(JSON.stringify(data));
JSFiddle
You need to have quotes around the value name
data = ('{"' + fields.productName.toString() + "":" + parseInt(fields.quantity.toString()) + '}' );
But you should not generate json manually, because now you would need to escape all quotes that fields.productName.toString() includes. You should use JSON.stringify instead.
链接地址: http://www.djcxy.com/p/45996.html下一篇: json.parse意外令牌错误