Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a String variable as key in a JSON object [duplicate]

Tags:

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.

like image 326
rontron Avatar asked Nov 20 '12 13:11

rontron


People also ask

Can JSON object have duplicate keys?

We can have duplicate keys in a JSON object, and it would still be valid.

Can JSON keys be strings?

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.

Can JSON have multiple keys with same name?

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".

How do you write a key-value pair in JSON?

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.


1 Answers

function constructJson(jsonKey, jsonValue){    var jsonObj = {"key1": jsonValue};    jsonObj[jsonKey] = "2";    return jsonObj; } 
like image 143
Anton Morozov Avatar answered Sep 28 '22 03:09

Anton Morozov