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.
We can have duplicate keys in a JSON object, and it would still be valid.
JSON object literals contains key/value pairs. Keys and values are separated by a colon. Keys must be strings, and values must be a valid JSON data type: string.
There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used. In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name".
Each key-value pair is separated by a comma, so the middle of a JSON lists as follows: "key" : "value", "key" : "value", "key": "value" . In the previous example, the first key-value pair is "first_name" : "Sammy" . JSON keys are on the left side of the colon.
function constructJson(jsonKey, jsonValue){ var jsonObj = {"key1": jsonValue}; jsonObj[jsonKey] = "2"; return jsonObj; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With