我有一个场景,在构造表单数据时,嵌套的JSON必须以线性方式序列化,因为这是服务器期望值的方式。所以,我写了一个小的递归函数来翻译JSON,就像这样:
{
"orderPrice":"11",
"cardNumber":"************1234",
"id":"8796191359018",
"accountHolderName":"Raj Pawan",
"expiryMonth":"02",
"expiryYear":"2019",
"issueNumber":null,
"billingAddress":{
"city":"Wonderland",
"code":"8796682911767",
"firstname":"Raj Pawan",
"lastname":"Gumdal",
"line1":"Addr Line 1",
"line2":null,
"state":"US-AS",
"region":{
"isocode":"US-AS"
},
"zip":"76767-6776"
}
}
变成这样:
{
"orderPrice":"11",
"cardNumber":"************1234",
"id":"8796191359018",
"accountHolderName":"Raj Pawan",
"expiryMonth":"02",
"expiryYear":"2019",
"issueNumber":null,
"billingAddress.city":"Wonderland",
"billingAddress.code":"8796682911767",
"billingAddress.firstname":"Raj Pawan",
"billingAddress.lastname":"Gumdal",
"billingAddress.line1":"Addr Line 1",
"billingAddress.line2":null,
"billingAddress.state":"US-AS",
"billingAddress.region.isocode":"US-AS",
"billingAddress.zip":"76767-6776"
}
服务器将接受这种转换格式的表单数据。
函数如下:
function jsonToFormData (inJSON, inTestJSON, inFormData, parentKey) {
// http://stackoverflow.com/a/22783314/260665
// Raj: Converts any nested JSON to formData.
var form_data = inFormData || new FormData();
var testJSON = inTestJSON || {};
for ( var key in inJSON ) {
// 1. If it is a recursion, then key has to be constructed like "parent.child" where parent JSON contains a child JSON
// 2. Perform append data only if the value for key is not a JSON, recurse otherwise!
var constructedKey = key;
if (parentKey) {
constructedKey = parentKey + "." + key;
}
var value = inJSON[key];
if (value && value.constructor === {}.constructor) {
// This is a JSON, we now need to recurse!
jsonToFormData (value, testJSON, form_data, constructedKey);
} else {
form_data.append(constructedKey, inJSON[key]);
testJSON[constructedKey] = inJSON[key];
}
}
return form_data;
}
调用:
var testJSON = {};
var form_data = jsonToFormData (jsonForPost, testJSON);
我使用testJSON只是为了查看转换后的结果,因为我无法提取form_data的内容。AJAX post call:
$.ajax({
type: "POST",
url: somePostURL,
data: form_data,
processData : false,
contentType : false,
success: function (data) {
},
error: function (e) {
}
});