包含 Array,Json,Function
的对象如何转成字符串
function obj2Str ( obj) {
switch ( typeof ( obj) ) {
case 'object' :
var ret = [ ] ;
if ( obj instanceof Array ) {
for ( var i = 0 , len = obj. length; i < len; i++ ) {
ret. push ( obj2Str ( obj[ i] ) ) ;
}
return '[' + ret. join ( ',' ) + ']' ;
}
else if ( obj instanceof RegExp ) {
return obj. toString ( ) ;
}
else {
for ( var a in obj) {
ret. push ( a + ':' + obj2Str ( obj[ a] ) ) ;
}
return '{' + ret. join ( ',' ) + '}' ;
}
case 'function' :
return 'function() {}' ;
case 'number' :
return obj. toString ( ) ;
case 'string' :
return "\"" + obj. replace ( /(\\|\")/g , "\\$1" ) . replace ( /\n|\r|\t/g , function ( a) { return ( "\n" == a) ? "\\n":(" \r"==a)?" \\r":(" \t"==a)?" \\t":" ";}) + " \"" ;
case 'boolean' :
return obj. toString ( ) ;
default :
return obj. toString ( ) ;
}
}
如何解析包含 Array ,Json,Function
的字符串为 Json
格式
var ast = acorn. parse ( res) . body[ 0 ] ;
for ( let nb of ast. declarations[ 0 ] . init. properties) {
nodeBinds[ nb. key. name] = res. data. substring ( nb. value. body. start, nb. value. body. end) ;
}