Reputation: 33
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.
Upvotes: 1
Views: 835
Reputation: 2435
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.
Upvotes: 2
Reputation: 14590
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));
Upvotes: 2
Reputation: 4911
Best way to avoid issues :
var data = {};
data[fields.productName.toString()] = parseInt(fields.quantity.toString());
P.S. Leverage the beauty of JS objects, Do not re-invent the wheel by constructing object using strings :)
Upvotes: 1