tools = ({
isJson: function (arg) {
if (null == arg) return false;
if (("string" == (typeof arg)) || (true == (arg instanceof Array)) || ("object" != (typeof arg)) || ("function" == (typeof arg))) return false;
return true;
},
trim: function (s) {
if (null == s) return s;
var space = ' ';
while (space == s.substr(0, 1)) {
s = s.substring(1);
}
while (space == s.substring(s.length - 1)) {
s = s.substr(0, s.length - 1);
}
return s;
},
isNumber: function (s) {
if (null == s) return false;
s = s.toString();
s = this.trim(s);
if (0 == s.length) return false;
if ('+' == s.substr(0, 1)) s = s.substr(1);
if ('-' == s.substr(0, 1)) s = s.substr(1);
var rg = /(^[0-9]$)|(^[1-9][0-9]*[0-9]$)|(^[0-9]\.[0-9]*[0-9]$)|(^[1-9][0-9]+\.[0-9]*[0-9]$)/;
return null != rg.exec(s);
},
jsonToStr: function (json) {
if (null == json) return "";
if (json instanceof HTMLElement) return '"HTMLElement Object [' + json.tagName + ']"';
if (null == this.jsonToStr.prototype.getElement) {
this.jsonToStr.prototype.me = this;
this.jsonToStr.prototype.getElement = (function (v) {
var v1 = null;
if (null == v) v = 'null';
if (v instanceof Array) {
v1 = this.me.jsonToStr.prototype.arrayFunc(v);
}
else if (this.me.isJson(v)) {
v1 = this.me.jsonToStr(v);
}
else {
var rg = /(^[0-9]$)|(^[1-9][0-9]*[0-9]$)|(^[0-9]\.[0-9]*[0-9]$)|(^[1-9][0-9]+\.[0-9]*[0-9]$)|(^true$)|(^false$)|(^null$)/;
v = v.toString().toLowerCase();
var vs = this.me.trim(v);
if (null == rg.exec(vs)) {
v = '"' + v + '"';
}
v1 = v;
}
return v1;
});
}
if (null == this.jsonToStr.prototype.arrayFunc) {
this.jsonToStr.prototype.arrayFunc = (function (arr) {
if (null == arr) return;
if (false == (arr instanceof Array)) return;
var a = '';
var len = arr.length;
for (var i = 0; i < len; i++) {
a += ', ' + this.getElement(arr[i]);
}
if (0 < a.length) a = a.substring(2);
a = '[' + a + ']';
return a;
});
}
var s = '';
for (var k in json) {
s += ', "' + k + '": ' + this.jsonToStr.prototype.getElement(json[k]);
}
if (0 < s.length) s = s.substring(2);
s = '{' + s + '}';
return s;
}
});
例:
var data = {
datas: [
[{ uid: 1, age: 23, email: ' abc@qq.com ' }, { uid: 2, age: 23, email: '123@qq.com' }],
[{ uid: 1, age: 33, email: 'abc123@qq.com' }, { uid: 2, age: 33, email: '123abc@qq.com' }]
],
message: '',
success: true
};
var jsonStr = tools.jsonToStr(data);
jsonStr = '{"datas": [[{"uid": 1, "age": 23, "email": " abc@qq.com "}, {"uid": 2, "age": 23, "email": "123@qq.com"}], [{"uid": 1, "age": 33, "email": "abc123@qq.com"}, {"uid": 2, "age": 33, "email": "123abc@qq.com"}]], "message": "", "success": true}';