13

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))
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
user2950593
  • 9,233
  • 15
  • 67
  • 131
  • 1
    @mplungjan: most likely the person voted to close because it would depend on the input given. The question could have used some clarification, but without a comment the questioner would have no idea what should have been done. Unless the question's really poor, people shouldn't be just doing hit-and-run voting. – Qantas 94 Heavy Dec 26 '13 at 09:07
  • Anyway, this is presuming that you haven't escaped it yourself yet, right? – Qantas 94 Heavy Dec 26 '13 at 09:08

4 Answers4

15

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

Raunak Kathuria
  • 3,185
  • 1
  • 18
  • 27
8

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
8

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

Community
  • 1
  • 1
Oranit Dar
  • 1,539
  • 18
  • 17
0

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

HDT
  • 2,017
  • 20
  • 32