28

Possible Duplicate:
Is a way that use var to create JSON object in key?

I would like to construct a JSON object in JavaScript by using the value of a (String) variable as the key. But what I got is the name of the variable as the key.

example.js:

function constructJson(jsonKey, jsonValue){
   var jsonObj = { "key1":jsonValue, jsonKey:2};
   return jsonObj;
}
 

The call

constructJson("key2",8);

returns a JSON -> {"key1":8,"jsonKey":2} but I would like to have {"key1":8,"key2":2}.

Does anyone know how to achieve this? seems like a simple problem but I cannot find the solution.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
rontron
  • 453
  • 2
  • 6
  • 14

1 Answers1

52
function constructJson(jsonKey, jsonValue){
   var jsonObj = {"key1": jsonValue};
   jsonObj[jsonKey] = "2";
   return jsonObj;
}
AlexStack
  • 16,766
  • 21
  • 72
  • 104
Anton Morozov
  • 1,090
  • 10
  • 7