0

I am trying to create a javascript object,

var systemName = {"system" : varA};

But I want the object to be in the form `{"system" :"varA"}

with varA having the variable value but inserted inside double quotes. I have tried {"system" : "'+ varA +'"}; but that did not do the trick. Can you point out what I am doing wrong here? I know its a simple things. But sometimes these small things get us stuck at certain points

Da Silva
  • 229
  • 1
  • 7
  • 17

3 Answers3

1

Try this instead

var systemName = {};
systemName.system = varA;

(or)

systemName["system"] = varA;
Navin
  • 594
  • 2
  • 11
1

You don't want to do this. You shouldn't do this. If it is a string, the JSON parser will handle it for you. Don't worry about adding quotes to it. There is no reason for you to put quotes around the literal value of the variable. You can put quotes around it at the time of output, if you need to to.

var varA = "Hello";
var systemName = {"system" : varA};

console.log(JSON.stringify(systemName));
// {"system":"Hello"} 

http://jsfiddle.net/FWBub/

But, if you must do so:

var varA = '"Hello"';
var systemName = {"system" : varA};

console.log(JSON.stringify(systemName));
{"system":"\"Hello\""} 

http://jsfiddle.net/FWBub/1

Ryan
  • 14,392
  • 8
  • 62
  • 102
0

JSON.stringify(varA) will add JSON quotes around the value.

Scimonster
  • 32,893
  • 9
  • 77
  • 89