Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify and encodeuricomponent

Tags:

javascript

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

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

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

return domain + '?x=' + encodeURIComponent(JSON.stringify(x))
like image 468
user2950593 Avatar asked Dec 25 '13 15:12

user2950593


2 Answers

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

JSON - JavaScript Object Notation

  • Use JSON.stringify when you have a JavaScript Object and you want to convert it to a string (containing a JSON text). This is called serialization.
  • Use JSON.parse when 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.

Regardless to JSON:

  • Use encodeURIComponent whenever you want to send "problematic" characters in the URL such as &, % etc. The opposite is decodeURIComponent.

I used these answers for my summary:

Difference between JSON.stringify and JSON.parse

difference between escape, encodeuri, encodeURIComponent

like image 186
Oranit Dar Avatar answered Oct 08 '22 03:10

Oranit Dar


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

like image 23
Raunak Kathuria Avatar answered Oct 08 '22 02:10

Raunak Kathuria