您所在的位置:小祥子 » 编程 » JavaScript » 正文

Object转换为JSON格式字符串

时间:2015-07-06 编辑:不平凡的我 来源:Cnblogs

简介:

JS的Object转换为Json字符串。

代码:

function (object) {
    // Object转换为josn
    var json = "";

    switch (jQuery.type(object)) {
        case "array":
            json = "[";

            $.each(object, function (i, item) {
                json += $.sinopec.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 + "\":" + $.sinopec.ObjectToJson(value) + ",";
                } else if (jQuery.type(value) == "array") {
                    json += "\"" + key + "\":" + $.sinopec.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"
    }
}
关键词:转换 JS 字符 字符串