Insert Javascript Variable into JSON Object

Viewed 9167

I have a JSON object like this:

var values = {
"email": " ' + fn + ' ", // This field is required to identify existing customers.
"first_name": "email",
"last_name": "email",
"address": "email",
"city": "email",
"state": "email",
"zip": "email",
"dob": "email" // This field must match the following format: YYYYMMDD. This field is also required
};

I am trying to insert:

var fn = 'Tom'; 

But the variable is not appearing. How can i go about this?

2 Answers

The problem is that " ' + fn + ' " is treated as a string so fn will never be replaced. What you're after is:

var fn = "Tom";

var values = {
"email": " " + fn + " ", // This field is required to identify existing customers.
"first_name": "email",
"last_name": "email",
"address": "email",
"city": "email",
"state": "email",
"zip": "email",
"dob": "email" // This field must match the following format: YYYYMMDD. This field is also required
};

You can just use email: fn if you dont need the space in the front and back

The standard way of using JSON with javascript is to create an object in your application, in this case it may look something like this

var values = {
   email: "Tom@whatever",
   name: "Tom"
}

You can interact with this object however you like, such as

values.city = "New York";

Then when you are ready to create a JSON object that represents that object, you can use JSON.stringify() MDN docs here

In this case

let jsonString = JSON.stringify(values);
console.log(jsonString);

yields this result:

{"email":"Tom@whatever","name":"Tom","city":"New York"}

This means you don't have to worry about creating a JSON string manually at all!

More info on JSON here

Related