javascript JSON.stringify 和 encodeuricomponent

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20774227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:16:26  来源:igfitidea点击:

JSON.stringify and encodeuricomponent

javascript

提问by user2950593

My string for my AJAX GET request looks like the following:

我的 AJAX GET 请求字符串如下所示:

return domain + '?x=' + JSON.stringify(x)

Do need to use encodeUriComponentto make the URI valid? For example:

是否需要使用encodeUriComponent以使 URI 有效?例如:

return domain + '?x=' + encodeURIComponent(JSON.stringify(x))

回答by Raunak Kathuria

JSON.stringifydoesn't escape characters, it just returns you string representation and as you are using it in url you need to escape it using encodeURIComponent

JSON.stringify不转义字符,它只返回字符串表示形式,当您在 url 中使用它时,您需要使用 encodeURIComponent

回答by Quentin

Yes. The JSON is expressed as a textand you are adding it as a component of a URI, so you should.

是的。JSON 表示为文本,您将其添加为 URI 的一个组件,因此您应该这样做。

回答by Oranit Dar

This is what I understand from reading some posts and answers (please feel free to correct me)

这是我从阅读一些帖子和答案中了解到的(请随时纠正我)

JSON - JavaScript Object Notation

JSON - ĴAVA小号CRIPT öbject Ñ浮选

  • Use JSON.stringifywhen you have a JavaScript Object and you want to convert it to a string (containing a JSON text). This is called serialization.
  • Use JSON.parsewhen you wish to convert a string (which contains a JSON text) to a JavaScript object (e.g. if you get a string containing a JSON text from the session storage and you want to convert it to JSON and use some of the fields of the object). This is called deserialization, and it is the opposite of JSON.stringify.
  • 当您有一个 JavaScript 对象并且想要将其转换为字符串(包含 JSON 文本)时,请使用JSON.stringify。这称为序列化。
  • 使用JSON.parse当你想为一个字符串(其中包含一个JSON文本)转换为JavaScript对象(例如,如果你得到一个包含从会话存储一个JSON文本字符串,并且希望将其转换为JSON和使用一些对象的字段)。这称为反序列化,与 JSON.stringify 正好相反。

Regardless to JSON:

不管是 JSON:

  • Use encodeURIComponentwhenever you want to send "problematic" characters in the URL such as &, % etc. The opposite is decodeURIComponent.
  • 使用encodeURIComponent方法,只要你想在URL发送“有问题”的字符,如&,%等相反的是decodeURIComponent。

I used these answers for my summary:

我将这些答案用于我的总结:

Difference between JSON.stringify and JSON.parse

JSON.stringify 和 JSON.parse 的区别

difference between escape, encodeuri, encodeURIComponent

转义、encodeuri、encodeURIComponent 之间的区别

回答by HDT

can use rc4 encode(or base64 if content not too length) in url then decode in process file

可以在 url 中使用 rc4 编码(或 base64,如果内容不太长)然后在进程文件中解码