我是新手,请耐心等待。
请指导我如何创建一个javascript数组,这反过来给我一个像这样的json。
{
"MotorInsurance": [{
"Service": "Compare",
"Data": [{
"Apikey": "1234",
"Process": "Compare",
"TransactionId": "32",
"Type": "New",
"Channel": "1"
}],
"Vehicle": [{
"VehicleCode": "456",
"RTOCode": "AP12",
"RegistrationYear": "2016"
}],
"User":[{
"IPAddress": "66",
"DateTime": "12-06-2016"
}]
}]
}
我试过这个:
var formData = {};
formData['MotorInsurance'] = {};
formData['MotorInsurance']['Service'] = "Compare";
formData['MotorInsurance']['Data'] = {};
formData['MotorInsurance']['Data']['Apikey'] = '1234';
formData['MotorInsurance']['Data']['Process'] = 'Compare';
formData['MotorInsurance']['Data']['TransactionId'] = '32';
formData['MotorInsurance']['Data']['Type'] = 'New';
formData['MotorInsurance']['Data']['Channel'] = '1';
formData['MotorInsurance']['Vehicle'] = {};
formData['MotorInsurance']['Vehicle']['VehicleCode'] = '';
formData['MotorInsurance']['Vehicle']['RTOCode'] = '';
formData['MotorInsurance']['Vehicle']['RegistrationYear'] = '';
formData['MotorInsurance']['User'] = {};
formData['MotorInsurance']['User']['IPAddress'] = '66.12.5.4';
formData['MotorInsurance']['User']['DateTime'] = '12-06-2016';
请指导我。感谢
答案 0 :(得分:1)
var formData = {};
formData['MotorInsurance'] = [{}];
formData['MotorInsurance'][0]['Service'] = "Compare";
formData['MotorInsurance'][0]['Data'] = [{}];
formData['MotorInsurance'][0]['Data'][0]['Apikey'] = '1234';
formData['MotorInsurance'][0]['Data'][0]['Process'] = 'Compare';
formData['MotorInsurance'][0]['Data'][0]['TransactionId'] = '32';
formData['MotorInsurance'][0]['Data'][0]['Type'] = 'New';
formData['MotorInsurance'][0]['Data'][0]['Channel'] = '1';
formData['MotorInsurance'][0]['Vehicle'] = [{}];
formData['MotorInsurance'][0]['Vehicle'][0]['VehicleCode'] = '';
formData['MotorInsurance'][0]['Vehicle'][0]['RTOCode'] = '';
formData['MotorInsurance'][0]['Vehicle'][0]['RegistrationYear'] = '';
formData['MotorInsurance'][0]['User'] = [{}];
formData['MotorInsurance'][0]['User'][0]['IPAddress'] = '66.12.5.4';
formData['MotorInsurance'][0]['User'][0]['DateTime'] = '12-06-2016';
document.write('<pre>' + JSON.stringify(formData, 0, 4) + '</pre>');
&#13;
答案 1 :(得分:0)
您的formData['MotorInsurance']
必须是数组:
formData['MotorInsurance'] = [];
然后你将在这个数组的第一个元素中创建其他所有内容:
formData['MotorInsurance'][0] = {};
formData['MotorInsurance'][0]['Service'] = "Compare";
Data
,Vehicule
和User
同样如此。
答案 2 :(得分:0)
您可以这样处理:对于嵌套对象,逐个填充它们(如下面的数据变量),然后在分配表单数据时,确保在变量周围放置方括号。
vehicle = {
"VehicleCode": "456",
"RTOCode": "AP12",
"RegistrationYear": "2016"
};
user = {
"IPAddress": "66",
"DateTime": "12-06-2016"
};
data = {
"Apikey": "1234",
"Process": "Compare",
"TransactionId": "32",
"Type": "New",
"Channel": "1"
};
service = {"Service": "Compare"}
o = {"Data": [data], "Vehicle": [vehicle], "User": [user], "Service": service}
formData["MotorInsurance"] = [o]