Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to safely use JSON.stringify

I get a JSON object, which I then stringify to var embed. The console.log looks like:

console.log(send_me_along)

{"provider_url":"https://www.site.com/","description":"Stuff, you’ll need to blah blah","title":"Person detail view & engagement","url":"https://www.site.com/","version":"1.0","provider_name":"site","type":"link"}

Then in ajax beforeSend I try to pass this along:

settings.data += '&embed_data=' + send_me_along;

This is where it breaks. I don't know why. Do you? Something send_me_along breaks and the JSON object never makes it to rails.

Started POST "/st" for 127.0.0.1 at 2012-01-12 17:20:25 -0800
Parameters: {"utf8"=>"✓", "authenticity_token"=>"MzDImoksi56IZ1Fa4ldM8jaFyBy61xaWt4bf3z0/3UQ=", "comment"=>{"content"=>"https://www.site.com", "mentions"=>"https://www.site.com"}, "commit"=>"", "embed_data"=>"{\"provider_url\":\"https://www.site.com/\",\"description\":\"Stuff, you’ll need to blah blah.\",\"title\":\"Person detail view ", "engagement\",\"url\":\"https://www.site.com/\",\"version\":\"1.0\",\"provider_name\":\"site\",\"type\":\"link\"}"=>nil, "id"=>"ae86c5b7a6"}

It appears as if the & in the title is messing up on the post. is there something that needs to be done w jQuery when using settings.data to not allow the stringified data to break everything?

Thanks

like image 700
Rachela Meadows Avatar asked Jan 13 '12 01:01

Rachela Meadows


People also ask

Is JSON Stringify safe?

stringify() is fine. Using the output of JSON. stringify() in a JavaScript context will result in the expected behavior.

Can JSON Stringify throw an error?

Error Handling parse(), JSON. stringify() may throw errors, so it should be wrapped in a try catch statement. The function throws a TypeError in two contexts: if a circular reference occurs in the Javascript object or if the Javascript object contains a BigInt. A replacer cannot catch or change these errors.

What is difference between JSON parse and JSON Stringify?

The JSON. parse() function is used to convert a string into a JavaScript object while the JSON. stringify() function is used to convert a JavaScript object into a string.

Is JSON parsing XSS safe?

Parsing JSON can be a dangerous procedure if the JSON text contains untrusted data. For example, if you parse untrusted JSON in a browser using the JavaScript “eval” function, and the untrusted JSON text itself contains JavaScript code, the code will execute during parse time.


1 Answers

If you're trying to pass a string of JSON as a url parameter you need to encode it so that special characters that have meaning in a url (like ampersands) will not break things. So something like:

settings.data += '&embed_data=' + encodeURIComponent(send_me_along)

More info on encodeURIComponent() at MDN.

like image 74
nnnnnn Avatar answered Oct 13 '22 06:10

nnnnnn