PDA

View Full Version : A doubt related to JSON arrays



codeexploiter
05-07-2007, 04:48 AM
Hi,

Please have a look at the following code



function show() {
var columnHeaders = [
{key:"id_no"},
];
var keyValue = columnHeaders[0].key;

var JSONArray2 = [{keyvalue:"testing"}];
}


In the above function what I am trying to achieve is to create a JSON array that will be like the following


JSONArray2 = [{"id_no":"testing"}]

The question is how I can specify a key value using a variable name in which the original key value I want to use?

Now below code



var keyValue = columnHeaders[0].key;

var JSONArray2 = [{keyvalue:"testing"}];

gives the following


JSONArray2 = [{keyvalue:"testing"}]

Please help me to understand this problem

Regards

CodeExploiter

mwinter
05-07-2007, 10:58 AM
The question is how I can specify a key value using a variable name in which the original key value I want to use?

Bracket notation:



object[variable] = value;

For instance,



var keyValue = columnHeaders[0].key,
jsonArray = [{}];

jsonArray[0][keyValue] = 'testing';

The property names in an object literals are themselves literals: either expressed as strings, numbers, or identifiers. However, the identifiers are not references to variables. Think instead of the identifier in variable declarations.

Mike

codeexploiter
05-07-2007, 12:36 PM
Hi mike,

Thanks a lot for the answer.

Regards

Codex

Twey
05-07-2007, 05:45 PM
However, note that numerical arrays aren't a part of the JSON specification.

mwinter
05-07-2007, 05:53 PM
However, note that numerical arrays aren't a part of the JSON specification.
Yes, they are, with regards to both Douglas Crockford's original description and RFC 4627 (also written by Crockford).

Mike

Twey
05-07-2007, 06:46 PM
Oh yes, so they are. My error.