Home  >  Article  >  Web Front-end  >  Javascript生成json的函数代码(可以用php的json_decode解码)_json

Javascript生成json的函数代码(可以用php的json_decode解码)_json

WBOY
WBOYOriginal
2016-05-16 17:52:541129browse

但是有个问题
虽然JS解码JSON非常方便,但是编码似乎没有什么好办法…
本着能懒即懒,不能懒也尽量懒的原则,古狗了一下
还真让我发现了
PHP里直接用json_decode就可以解码,用起来相当方便

复制代码 代码如下:

function json_encode_js(aaa){
function je(str){
var a=[],i=0;
var pcs="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for (;iif(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(",")+"}";
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn