A-A+
javascript生成json可利用php json_decode解析
本文章自己 写了一个和php json生成函数一样的js文件,生成的json文件可以直接利用 php json_decode()函数来正常解析,代码如下:
- function json_encode_js(aaa){
- function je(str){
- var a=[],i=0;
- var pcs="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- for (;i<str.length;i++){
- if(pcs.indexOf(str[i]) == -1)
- a[i]="\u"+("0000"+str.charCodeAt(i).toString(16)).slice(-4);
- else
- a[i]=str[i];
- }
- return a.join("");
- }
- var i,s,a,aa=[];
- if(typeof(aaa)!="object") {alert("ERROR json");return;}
- for(i in aaa){
- s=aaa[i];
- a='"'+je(i)+'":';
- if(typeof(s)=='object'){
- a+=json_encode_js(s);
- }else{
- if(typeof(s)=='string')
- a+='"'+je(s)+'"';
- else if(typeof(s)=='number')
- a+=s;
- }
- aa[aa.length]=a;
- }
- return "{"+aa.join(",")+"}";
- }
原理我们是按照php的json_code函数来做的自然反解析时可直接使用php的json_decode函数来解析了。