将Javascript变量插入JSON对象

时间:2018-09-13 21:24:41

标签: javascript html variables frontend

我有一个像这样的JSON对象:

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
};

我正在尝试插入:

var fn = 'Tom'; 

但是没有出现该变量。我该怎么办?

2 个答案:

答案 0 :(得分:3)

将JSON与javascript结合使用的标准方法是在应用程序中创建一个对象,在这种情况下,它看起来可能像这样

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

您可以根据需要与该对象进行交互,例如

values.city = "New York";

然后,当您准备创建代表该对象的JSON对象时,可以使用JSON.stringify() MDN文档here

在这种情况下

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

产生以下结果:

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

这意味着您完全不必担心手动创建JSON字符串!

有关JSON here

的更多信息

答案 1 :(得分:2)

问题在于," ' + fn + ' "被视为字符串,因此fn将永远不会被替换。您所追求的是:

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
};

如果您不需要前面和后面的空格,则可以只使用email: fn