26

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
  • 5,808
  • 1
  • 22
  • 57
rontron
  • 433
  • 2
  • 6
  • 14

1 Answers1

52
function constructJson(jsonKey, jsonValue){
   var jsonObj = {"key1": jsonValue};
   jsonObj[jsonKey] = "2";
   return jsonObj;
}
AlexStack
  • 15,377
  • 18
  • 69
  • 102
Anton Morozov
  • 1,100
  • 10
  • 7