Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting textarea value into a valid JSON string

I am trying to make sure input from user is converted into a valid JSON string before submitted to server.

What I mean by 'Converting' is escaping characters such as '\n' and '"'. Btw, I am taking user input from HTML textarea.

Converting user input to a valid JSON string is very important for me as it will be posted to the server and sent back to client in JSON format. (Invalid JSON string will make whole response invalid)

If User entered

Hello New World,
My Name is "Wonderful".

in HTML <textarea>,

var content = $("textarea").val();

content will contain new-line character and double quotes character.

It's not a problem for server and database to handle and store data.

My problem occurs when the server sends back the data posted by clients to them in JSON format as they were posted.

Let me clarify it further by giving some example of my server's response. It's a JSON response and looks like this

{ "code": 0, "id": 1, "content": "USER_POSTED_CONTENT" }

If USER_POSTED_CONTENT contains new-line character '\n', double quotes or any characters that are must be escaped but not escaped, then it is no longer a valid JSON string and client's JavaScript engine cannot parse data.

So I am trying to make sure client is submitting valid JSON string.

This is what I came up with after doing some researches.

String.prototype.escapeForJson = function() {
  return this
    .replace(/\b/g, "")
    .replace(/\f/g, "")
    .replace(/\\/g, "\\")
    .replace(/\"/g, "\\\"")
    .replace(/\t/g, "\\t")
    .replace(/\r/g, "\\r")
    .replace(/\n/g, "\\n")
    .replace(/\u2028/g, "\\u2028")
    .replace(/\u2029/g, "\\u2029");
};

I use this function to escape all the characters that need to be escaped in order to create a valid JSON string.

var content = txt.val().escapeForJson();
$.ajax(
   ...
   data:{ "content": content }
   ...
);

But then... it seems like str = JSON.stringify(str); does the same job!

However, after reading what JSON.stringify is really for, I am just confused. It says JSON.stringify is to convert JSON Object into string.

I am not really converting JSON Object to string.

So my question is... Is it totally ok to use JSON.stringify to convert user input to valid JSON string object??

UPDATES:

JSON.stringify(content) worked good but it added double quotes in the beginning and in the end. And I had to manually remove it for my needs.

like image 978
Eddie Avatar asked Nov 25 '25 17:11

Eddie


2 Answers

Yep, it is totally ok. You do not need to re-invent what does exist already, and your code will be more useable for another developer.

EDIT: You might want to use object instead a simple string because you would like to send some other information.

For example, you might want to send the content of another input which will be developed later.

You should not use stringify is the target browser is IE7 or lesser without adding json2.js.

like image 123
Didier Aupest Avatar answered Nov 28 '25 06:11

Didier Aupest


I don't think JSON.stringify does what you need. Check the out the behavior when handling some of your cases:

JSON.stringify('\n\rhello\n')
*desired : "\\n\\rhello\\n"
*actual  : "\n\rhello\n"

JSON.stringify('\b\rhello\n')
*desired : "\\rhello\\n"
*actual  : "\b\rhello\n"

JSON.stringify('\b\f\b\f\b\f')
*desired : ""
*actual  : ""\b\f\b\f\b\f""

The stringify function returns a valid JSON string. A valid JSON string does not require these characters to be escaped.

The question is... Do you just need valid JSON strings? Or do you need valid JSON strings AND escaped characters? If the former: use stringify, if the latter: use stringify, and then use your function on top of it.

Highly relevant: How to escape a JSON string containing newline characters using javascript?

like image 27
Toby Liu Avatar answered Nov 28 '25 05:11

Toby Liu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!