Javascript 将json编码为字符串
我很感兴趣的是谷歌如何对POST参数进行编码。 在一个应用程序中,我发现了以下方法,假设我有以下对象:Javascript 将json编码为字符串,javascript,encryption,encoding,Javascript,Encryption,Encoding,我很感兴趣的是谷歌如何对POST参数进行编码。 在一个应用程序中,我发现了以下方法,假设我有以下对象: selection={"ty":"mc","cl":{"loc_type":0,"si":9,"aps":false},"sr":[]} 在POST请求中,它采用以下形式: selection=%7B%22ty%22%3A%22mc%22%2C%22cl%22%3A%7B%22loc_type%22%3A0%2C%22si%22%3A9%2C%22aps%22%3Afalse%7D%2C%
selection={"ty":"mc","cl":{"loc_type":0,"si":9,"aps":false},"sr":[]}
在POST请求中,它采用以下形式:
selection=%7B%22ty%22%3A%22mc%22%2C%22cl%22%3A%7B%22loc_type%22%3A0%2C%22si%22%3A9%2C%22aps%22%3Afalse%7D%2C%22sr%22%3A%5B%5D%7D
这里使用的是哪种方法?它被称为URL编码 它将非ASCII字符和在URI方案中具有特殊含义的字符替换为ASCII表示:每个不可打印的字符将被写入
%xy
,其中xy
是该字符的ASCII表内的索引
有许多编程语言支持开箱即用:
- 在JavaScript中,可以使用encodeURIComponent()或encodeURI()函数
var myjson = '{my:json}';
url_encoded_json = encodeURIComponent( myjson );
alert(url_encoded_json);
其他语文:
- PHP具有rawurlencode()函数
- ASP具有Server.URLEncode()函数
- Python具有urllib.urlencode()函数
- Java具有Java.net.URI(url).toASCIIString()函数
- 这只是URL编码
查看内置函数encodeURIComponent(str)和encodeURI(str)javascript中的方法称为
encodeURIComponent()
write
alert(encodeURIComponent('{"ty":"mc","cl":{"loc_type":0,"si":9,"aps":false},"sr":[]}'));
使用
encodeURIComponent
和JSON可以达到相同的效果。stringify
函数:
"selection=" + encodeURIComponent(JSON.stringify(selection))