0

I want to add a field to JSON. I do have a working solution, but it's ugly (using eval). Is there a nicer way to add a field?

var json = {};
var id = "test";
eval("json." + id + " = 5;");
console.log(json.test);

UPDATE: Sorry, my question was somewhat unclear. I want to use the variable id, which has the value of the new field.

Cheers, Bernhard

Bernie
  • 1,607
  • 1
  • 18
  • 30
  • 1
    `json[id] = 5`. Also, that's a JavaScript object, not JSON, don't get them mixed up! http://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation – Joe Clay Jun 09 '16 at 09:00
  • 2
    That's not JSON, that's a javascript object. You seem to want to add a property with a certain value. No offense, but searching online should easily yield useful results. Are we missing some info? – Jeroen Jun 09 '16 at 09:00
  • 1
    please have a look here: http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – Nina Scholz Jun 09 '16 at 09:02
  • obj.id = 5, JSON.stringify(obj) – Srle Jun 09 '16 at 09:03

3 Answers3

4

You can use like below instead:

Use like this:

json[id] = 5; 

Thus, in your case:

var json = {};
var id = "test";
json[id] = 5;
console.log(json.test); //will print 5
// OR
console.log(json['test']); //will print 5
Krishnakant
  • 435
  • 1
  • 6
  • 12
2

you can add like this :

var json = {};
json.test = 5;
console.log(json.test);

or

var json = {};
json["test"] = 5;
console.log(json.test);

Hope it helps :)

Arun AK
  • 4,353
  • 2
  • 23
  • 46
0

You can use

var json = {};
var id = "test";
eval("json." + id + " = 5;");
console.log(json.test);

and this

var json2 = {};
json2.test = 5;
console.log(json2.test);

or this

var json3 = {};
json3["test"] = 5;
console.log(json3.test);

First example is undesirable.

Razvan Dumitru
  • 11,815
  • 5
  • 34
  • 54