A simple implementation of Javascript JSON object and string conversion
function Obj2str (o) {
var r = [];
if (typeof o = = "string" | | o = = NULL) {return
o;
}
if (typeof o = = "Object") {
if (!o.sort) {
r[0]= "{" For
(var i in O) {
r[r.length]=i;
R[r.length]= ":";
R[r.length]=obj2str (O[i]);
R[r.length]= ",";
}
R[r.length-1]= "}"
}else{
r[0]= "[" For
(var i =0;i<o.length;i++) {
r[r.length]=obj2str (O[i]) ;
R[r.length]= ",";
}
R[r.length-1]= "]"
} return
R.join ("");
}
return o.tostring ();
}
String to Object
function Taoran () {
var str= ' {' Result ': ["219"], ["Bank", "121"], ["Refund", "272"], ["Failed to mention", "16"], ["Group purchase", "15"], [ "Taobao", "412"],["Taiwan", "58"], ["The Present Limit", "16"], ["Time To Date", "81"], ["Taiwan certification", "the"]]} ';
Alert (Strtoobj (str). result[2]);
function Strtoobj (JSON) {return
eval ("(" +json+) ");
}
A very useful jsontostring method
'
jsontostring code
function jsontostring (o) {
var arr = [];
var FMT = function (s) {
if (typeof s = = ' object ' && s!= null) return jsontostr (s);
Return/^ (String|number) $/.test (typeof s)? "" + S + "'": S;
}
for (var i in O)
arr.push ("' + i +" ': "+ FMT (O[i]));
Return ' {' + arr.join (', ') + '} ';
I used it anyway, haha.
Also: If you do not want the numbers in JSON to be serialized. Can be modified: return/^ (String|number) $/.test (typeof s)? ' "' + S + '" ': s; is: Return/^ (String) $/.test (typeof s)? ' "' + S + '" ': s; (It's just ignoring the number type.)
function o2string (O) {
//return json.stringify (jsonobj);
var S = [];
var J = "";
if (Object.prototype.toString.apply (O) = = ' [Object Array] ') {for
(var i = 0; i < o.length; i++)
S.push (O2stri Ng (O[i]));
J = ' [' + s.join (', '] + '] ';
}
else if (Object.prototype.toString.apply (O) = = ' [Object Date] ') {
J = ' new Date (' + o.gettime () + ') ';
}
else if (Object.prototype.toString.apply (O) = = ' [Object RegExp] ' | | Object.prototype.toString.apply (O) = = ' [object Function] ') {
J = o.tostring ();
}
else if (Object.prototype.toString.apply (O) = = ' [Object] ') {for
(var i in O) {
o[i] = typeof (O[i)) = = ' String '? ' "' + o[i] + '" ': (typeof (o[i)) = = = ' object '? O2string (O[i]): O[i]);
S.push (' "' + i + '": ' + o[i]);
}
J = ' {' + s.join (', ') + '} ';
}
return J;
Json.stringify (Jsonobj)
Json.stringify (jsonobj) is the easiest way to do it, but there are browser compatibility issues (for Ie8+,chrome 1+,ff 3+ only)
The above is a small series for you to bring JavaScript JSON object and string to convert each other simple realization of the whole content, hope to help everyone, a lot of support cloud Habitat Community ~