0

I have a standard JSON 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 orginalJson. I then add a top level key as text

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

gives

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

expecting

{ "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 push but I have not had any luck understanding the correct syntax.

2 Answers 2

1

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"}]}
Sign up to request clarification or add additional context in comments.

Comments

0

You have to first create the object, then use bracket notation for the key
Because you're using the same variable to hold the newly modified value, we'll need a temporary object.
The better option would probably be to not use the same variabel twice

var orginalJson = '{"test":"test"}';

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

tempObj[newVar] = newJson;

newJson = tempObj;

console.log(newJson)

Or in ES2015 you can use dynamic keys

var orginalJson = '{"test":"test"}';

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

newJson = { [newVar]: newJson };

console.log(newJson);

1 Comment

thanks for the code. This answer does work and explains the process. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.