Convert an Object to a JSON string, objectjson
Introduction:
Convert JavaScript objects to Json strings.
Code:
Function ObjectToJson (object) {// convert the Object to 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 ;}
Example:
var data = {};data['Username'] = $('#username').val();data['Password'] = $('#password').val();var params = {};params['url'] = '/Demo/SignIn';params['data'] = data;
Result:
{ "url": "/Demo/SignIn", "data": { "Username": "demo", "Password": "test" }}