简体   繁体   English

JSON.stringify和encodeuricomponent

[英]JSON.stringify and encodeuricomponent

My string for my AJAX GET request looks like the following: 我的AJAX GET请求的字符串如下所示:

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

Do need to use encodeUriComponent to make the URI valid? 是否需要使用encodeUriComponent来使URI有效? For example: 例如:

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

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

Yes. 是。 The JSON is expressed as a text and you are adding it as a component of a URI, so you should. JSON表示为文本 ,您将其添加为URI的组件,因此您应该这样做。

This is what I understand from reading some posts and answers (please feel free to correct me) 这是我通过阅读一些帖子和答案所理解的(请随时纠正我)

JSON - J ava S cript O bject N otation JSON - J ava S cript O bject N otation

  • Use JSON.stringify when you have a JavaScript Object and you want to convert it to a string (containing a JSON text). 如果您有JavaScript对象并且想要将其转换为字符串(包含JSON文本),请使用JSON.stringify This is called serialization. 这称为序列化。
  • Use JSON.parse when you wish to convert a string (which contains a JSON text) to a JavaScript object (eg 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). 当您希望将字符串(包含JSON文本)转换为JavaScript对象时,请使用JSON.parse (例如,如果您从会话存储中获取包含JSON文本的字符串,并且您希望将其转换为JSON并使用其中一些对象的字段)。 This is called deserialization, and it is the opposite of JSON.stringify. 这称为反序列化,它与JSON.stringify相反。

Regardless to JSON: 无论JSON如何:

  • Use encodeURIComponent whenever you want to send "problematic" characters in the URL such as &, % etc. The opposite is decodeURIComponent. 每当要在URL中发送“有问题”字符时使用encodeURIComponent,例如&,%等。相反的是decodeURIComponent。

I used these answers for my summary: 我将这些答案用于我的总结:

Difference between JSON.stringify and JSON.parse JSON.stringify和JSON.parse之间的区别

difference between escape, encodeuri, encodeURIComponent escape,encodeuri,encodeURIComponent之间的区别

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM