关闭

Object转换为JSON格式字符串

标签: web前端javascript
226人阅读 评论(0) 收藏 举报
分类:
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;
}
<pre name="code" class="javascript">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"
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:14515次
    • 积分:622
    • 等级:
    • 排名:千里之外
    • 原创:46篇
    • 转载:25篇
    • 译文:0篇
    • 评论:1条
    文章分类
    文章存档