0

I am trying to create a json which contains a key value pair where the value is generated based on a concatenation of another two variables(strings).

Apart from concatenating like,

var a = "A";
var b = "B";
var c = a+" "+b;

and using variable 'c' directly, is there a way to append variables within the key value as below.

var fName = "Test1";
var lName = "Test2";

var json = {"fname":fname,"lname":lName,"fullname":"'fName'+' '+'lname'"}

I expect to result {"fname":"Test1","lname":"Test2","fullname":"Test1 Test2"}

Please let me know if this is possible to achieve.

1

1 Answer 1

1
var fName = "Test1";
var lName = "Test2";

var json = {"fname":fName,"lname":lName,"fullname": fName + " " + lName}

Edit: Following the comments, I'll illustrate other ways to play with JSON strings and objects...

// json is a JavaScript Object
typeof json  // -> "object"

// If you want to create JSON string representing it, use JSON.stringify()
var jsonString = JSON.stringify(json)

typeof jsonString  // -> "string"

// If you like pain, you can also build that string manually
// with the right escape sequences... (Do not do that)
var sillyJsonString = "{\"fname\":" + "\""+fName + "\",\"lname\":" + "\"" + lName + "\",\"fullname\":" + "\""+fName + " " + lName + "\"}"

typeof sillyJsonString  // -> "string"

// And now let's make sure they have the same content
jsonString === sillyJsonString  // -> true

// And the final part, re-create the object for JSON string
var sameJsonObject = JSON.parse(sillyJsonString)

// Now let's compare that the objects have the same content (but the are not equal ;))
JSON.stringify(json) === JSON.stringify(sameJsonObject)  // -> true

Hope this will point you in the right direction...

Sign up to request clarification or add additional context in comments.

6 Comments

I am passing effective json within double quotes as below. ``` "{"fname":fName,"lname":lName,"fullname": fName + " " + lName}" ``` Any escape character or any method to use this
What exactly are you trying to do? Do you want to parse some JSON? Create a JSON string? If you parse it, where do you take it from? What are these "triple single quote"?
Triple quotes added to format the code in comment. Ignore that please, Thank you for the clarification. I am trying to update json on the fly. Seems it's not possible. So I will create a new variable with merged values. Thanks for your support Antony.
What do you mean by on the fly? If json is an object, not a string (like in your original question), you can add properties to it: json["newKey"] = "newValue"
Apologies for the confusion. Json is a string in this case. It's a hassle and I am considering a different approach. 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.