1

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.

3
  • What is the value of fields.productName and fields.quantity? Commented Dec 13, 2015 at 10:33
  • 2
    Do not generate JSON manually, especially when you don't know the JSON syntax. Create an object and leave the stringification to JSON.stringify. Commented Dec 13, 2015 at 10:34
  • It's strings i get from a form Commented Dec 13, 2015 at 10:34

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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

2 Comments

i'm getting [Object Object] SyntaxError: Unexpected token o
Are you trying to do alert()? If so, Always remember to stringify JS objects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.