Convert a multidimensional javascript array to JSON?

后端 未结 9 1173
半阙折子戏
半阙折子戏 2020-12-05 09:54

What is the best way of converting a multi-dimensional javascript array to JSON?

9条回答
  •  庸人自扰
    2020-12-05 10:21

    This will convert all combinations of arrays within objects and vice versa including function names:

    function isArray(a){var g=a.constructor.toString();
       if(g.match(/function Array()/)){return true;}else{return false;}
    }
    function objtostring(o){var a,k,f,freg=[],txt; if(typeof o!='object'){return false;}
       if(isArray(o)){a={'t1':'[','t2':']','isarray':true}
       }else         {a={'t1':'{','t2':'}','isarray':false}}; txt=a.t1;
       for(k in o){
               if(!a.isarray)txt+="'"+k+"':";
               if(typeof o[k]=='string'){txt+="'"+o[k]+"',";
               }else if(typeof o[k]=='number'||typeof o[k]=='boolean'){txt+=o[k]+",";
               }else if(typeof o[k]=='function'){f=o[k].toString();freg=f.match(/^function\s+(\w+)\s*\(/);
                   if(freg){txt+=freg[1]+",";}else{txt+=f+",";};
               }else if(typeof o[k]=='object'){txt+=objtostring(o[k])+",";
               }
       }return txt.substr(0,txt.length-1)+a.t2;
    }
    

提交回复
热议问题