简介:
把JS的Object转换为Json字符串。
代码:
function ObjectToJson(object) {
// Object转换为josn
var json = ""; switch (jQuery.type(object)) {
case "array":
json = "["; $.each(object, function (i, item) {
json += ObjectToJson(item) + ",";
}); if (json != "[" && json.length > 0) json = json.substr(0, json.length - 1); json += "]"; break; case "object":
json = "{"; $.each(object, function (key, value) {
if (jQuery.type(value) == "object") {
json += "\"" + key + "\":" + ObjectToJson(value) + ",";
} else if (jQuery.type(value) == "array") {
json += "\"" + key + "\":" + ObjectToJson(value) + ",";
} else {
json += "\"" + key + "\":\"" + value + "\",";
}
}); if (json != "{" && json.length > 0) json = json.substr(0, json.length - 1); json += "}"; break; default:
json = "\"" + object + "\"";
break;
} return json;
}
示例:
var data = {};
data['Username'] = $('#username').val();
data['Password'] = $('#password').val(); var params = {};
params['url'] = '/Demo/SignIn';
params['data'] = data;
结果:
{
"url": "/Demo/SignIn",
"data": {
"Username": "demo",
"Password": "test"
}
}