art vanderlay art vanderlay - 3 years ago 116
Javascript Question

node,js add an outer level to json using a variable as key name

I have a standard

stored in a variable and am able to add a top level key when directly using text but a variable,

[{"myKey":"my value"}]

is stored in
. I then add a top level key as text

var newJson = JSON.parse(orginalJson);
newJson = { myText: newJson };


{ "myText": [{"myKey":"my value"}]}

I would now like to replace the text in the code with a variable

var newVar = "newtext";
var newJson = JSON.parse(orginalJson);
newJson = { newVar: newJson };

however I do not get the var value as expected, just the name of var not the value


{ "newtext": [{"myKey":"my value"}]}

but get

{ "newVar ": [{"myKey":"my value"}]}

what is the correct way to use a var in this instance. I have read other posts suggesting using a
but I have not had any luck understanding the correct syntax.

Answer Source

The correct way of using var is;

var newVar = "newText"
var newJson = {}
newJson[newVar] = JSON.parse(originalJson)

This will give you

{ "newVar ": [{"myKey":"my value"}]}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download