almog
almog

Reputation: 33

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.

Upvotes: 1

Views: 835

Answers (3)

FINDarkside
FINDarkside

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

michelem
michelem

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));

JSFiddle

Upvotes: 2

Eswar Rajesh Pinapala
Eswar Rajesh Pinapala

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

Related Questions