我有这段代码:
function my_json_function(my_variable) {
var json_var = {
my_variable: [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"lastName": "Smith"
}]
};
return json_var;
}
所以,问题是:
我将一个名为my_variable
的变量传递给函数,我想将它分配给json组的名称。
所以,我解释一下我的意思:
例如,如果my_variable = "employees"
,函数必须产生以下结果:
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"}
]
我试图像这样投射:String(my_variable)
,但它返回错误:
Uncaught SyntaxError: Unexpected token :
答案 0 :(得分:3)
您需要使用括号括号:
var json_var = {};
json_var[my_variable] = [
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"}
];
在对象文字中,不可能有基于动态密钥的名称。
答案 1 :(得分:2)
请参阅代码中的内联注释:
function my_json_function(my_variable) {
var json_var = {
peoples: [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"lastName": "Smith"
}]
};
var obj = {}; // Create empty object
obj[my_variable] = json_var.peoples; // Assign the data in the new key
return obj; // return newly created object
}
答案 2 :(得分:0)
您需要使用括号表示法而不是点符号。
<bean id="dataSource"
class = "com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
<property name="driverClass" value="oracle.jdbc.OracleDriver" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
<property name="maxPoolSize" value="50"/>
<property name="initialPoolSize" value="2"/>
<property name="minPoolSize" value="1"/>
<property name="maxStatements" value="200"/>
<property name="maxIdleTime" value="300"/>
<property name="acquireIncrement" value="10"/>
<property name="unreturnedConnectionTimeout" value="90"/>
<property name="maxConnectionAge" value="120"/>
</bean>
请注意使用带有方括号的function my_json_function(my_variable) {
var json_var = {};
json_var[my_variable] = [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"lastName": "Smith"
}];
return json_var;
}
。这将在对象中创建一个属性,并传入任何变量。