Setting JSON key from a variable?

M

Mark Smith

Hi,

I am trying to build a json object from a predefined variable. But the
variable name is being interpreted as a literal string rather than the
contents of the variable.

For example the following code displays "NONE" rather than the
contents of the variable "_nothingselected_":

<script>
var NONE="_nothingselected_";
var jsonOptions={ NONE : "Please Select" };
for(index in jsonOptions)
{
alert(index);
}
</script>

What is the correct way to do this?

Thanks
 
J

Jorge

Hi,

I am trying to build a json object from a predefined variable. But the
variable name is being interpreted as a literal string rather than the
contents of the variable.

For example the following code displays "NONE" rather than the
contents of the variable "_nothingselected_":

<script>
var NONE="_nothingselected_";
var jsonOptions={ NONE : "Please Select" };
for(index in jsonOptions)
{
 alert(index);}

</script>

What is the correct way to do this?

var jsonOptions= {};
jsonOptions[NONE]= "Please Select";
 
T

Thomas 'PointedEars' Lahn

Mark said:
I am trying to build a json object from a predefined variable. But the
variable name is being interpreted as a literal string rather than the
contents of the variable.

For example the following code displays "NONE" rather than the
contents of the variable "_nothingselected_":

<script>

var NONE="_nothingselected_";
var jsonOptions={ NONE : "Please Select" };
for(index in jsonOptions)
{
alert(index);
}
</script>

What is the correct way to do this?

var jsonOptions = {};
jsonOptions[NONE] = "Please Select";

Asked at least a hundred times already, and well-documented. RTFM, RTFFAQ,
STFW.

<http://jibbering.com/faq/#posting>

See also: <https://developer.mozilla.org/En/Using_native_JSON>.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top