Alex Rivera | Logout

How to use a String variable as key in a JSON object

Asked 2012-11-20T13:17:02.613
31

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.

Edit
Report

1 Answer

52
function constructJson(jsonKey, jsonValue){
   var jsonObj = {"key1": jsonValue};
   jsonObj[jsonKey] = "2";
   return jsonObj;
}
answered 2012-11-20T13:19:19.313

Your Answer