Bernie Bernie - 5 months ago 19
JSON Question

Add field to JSON

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

Answer

You can use like below instead:

Syntax:

json[id] = 5; 
Comments