Skip to content

Instantly share code, notes, and snippets.

@JoshyFrancis
Last active May 22, 2018 09:18
Show Gist options
  • Save JoshyFrancis/f9d2395cb342fe71301b81416495c92e to your computer and use it in GitHub Desktop.
Save JoshyFrancis/f9d2395cb342fe71301b81416495c92e to your computer and use it in GitHub Desktop.
Stringify a javascript object to string(not JSON) and vice versa
function js_stringify(obj){
switch(typeof(obj)){
case 'string':
return '"'+ obj + '"' ;
break;
case 'undefined':case 'number':case 'boolean': case 'null':
//undefined=String(undefined);
return String(obj) ;
break;
case 'function':
return obj.toString();
break;
case 'object':
if (!obj) {
return "null";
}
if (obj instanceof Date){
//return '(new Date("' + obj.toISOString() + '"))';
//d=new Date("2018-05-22T06:34:28.659Z");
//return 'function(){ return new Date('+obj.getTime()+');}()';
return 'new Date("' + obj.toISOString() + '")';
}else{
if (!Array.isArray) {
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
}
}
//if (Object.prototype.toString.call(obj) == '[object Array]') {
//if(Array.isArray (obj)){
var is_array=obj.constructor === Array;
if(is_array){
var str='[';
var l = obj.length;
var j=0;
for (var i = 0; i < l; i++) {
if(j>0){
str+=',';
}
str+=js_stringify(obj[i]) ;
j+=1;
}
str+=']';
return str;
}else{//object
var str='{';
var j=0;
for(var a in obj){
if(j>0){
str+=',';
}
str+=String(a) + ':' + js_stringify(obj[a]) ;
j+=1;
}
str+='}';
return str;
}
}
break;
}
/* in console
var a={m:[[0,1],[0,2],[0,3]]};
var a={a:function (){alert("ok");},b:function(){ return new Date(1526975358084);}(),c:[1,2,3],d:'sdsd',e:true,f:123};
var a={a:'dds',x:10,d:new Date(),ar:[1,2,3] ,obj:{ t:'t', q:[4,5,6]} ,m:[[0,1],[0,2],[0,3]] ,f:function(){alert('ok');} };
var b=js_stringify(a);
eval('var c='+ b + ';');
c;
// or
var c = new Function('return ' + b )();
c;
*/
/*
* All honour and glory and thanks and praise and worship belong to him, my Lord Jesus Christ.
* All honour and glory and thanks and praise and worship belong to him, my Lord Jesus Christ.
* All honour and glory and thanks and praise and worship belong to him, my Lord Jesus Christ.
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment