将JSON编码为字符串

3
我很感兴趣谷歌是如何对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%22sr%22%3A%5B%5D%7D

这里应用了哪种方法?
4个回答

1
可以使用encodeURIComponentJSON.stringify函数来实现相同的效果:
"selection=" + encodeURIComponent(JSON.stringify(selection))

0

这只是URL编码

请查看内置函数encodeURIComponent(str)和encodeURI(str)


0

这被称为URL编码。

它用ASCII表示法替换非ASCII字符和在URI方案中具有特殊含义的字符:每个不可打印的字符将被写成%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()函数。

0

在 JavaScript 中,该方法被称为 encodeURIComponent(),请编写。

alert(encodeURIComponent('{"ty":"mc","cl":{"loc_type":0,"si":9,"aps":false},"sr":[]}'));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接