Home  >  Article  >  Web Front-end  >  Javascript generates json function code (can be decoded with php's json_decode)_json

Javascript generates json function code (can be decoded with php's json_decode)_json

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

But there is a problem
Although JS is very convenient to decode JSON, there seems to be no good way to encode it...
In line with the principle of being lazy if you can, and being as lazy as possible if you can’t be lazy, Gugou gave it a try
It really made it easier I discovered
You can decode it directly using json_decode in PHP, which is very convenient to use

Copy the code The code is as follows:

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