Convert textarea value to valid JSON string

I am trying to make sure that input from the user is converted to a valid JSON string before being sent to the server.

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

.

Converting the user input to a valid JSON string is very important to me as it will be sent to the server and sent back to the client in JSON format. (An invalid JSON string will invalidate the entire response)

If the user entered

Hello New World,
My name is "Wonderful".

in HTML <textarea>

,

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

      

the content will contain a newline character and a double quote.

This is not a problem for the server and database to process and store data.

My problem occurs when the server sends back the data sent by clients in JSON format as it is published.

Let me clarify this by providing an example of my server response. This is the JSON response and looks like this

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

      

If it USER_POSTED_CONTENT

contains the newline character '\ n', double quotes, or any characters that must be escaped but not escaped, then it is no longer a valid JSON string and the client JavaScript engine cannot parse the data.

So I am trying to make sure the client is sending a valid JSON string.

Here's what I came up with after some research.

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 am using this function to avoid all characters that need to be escaped to create a valid JSON string.

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

      

But then ... it looks like it str = JSON.stringify(str);

does the same job!

However, after reading what JSON.stringify

really is, I'm just confused. It says it JSON.stringify

is about converting a JSON object to a string.

I don't really convert JSON object to string.

So my question is ... Is it possible to use JSON.stringify

JSON strings to convert user input to valid object?

UPDATE:

JSON.stringify (content) worked well, but it added double quotes at the beginning and end. And I had to manually uninstall it for my needs.

+3


source to share


3 answers


Yes, it's okay. You don't need to reinvent what already exists and your code will be more useful to another developer.

EDIT: You can use an object instead of a simple string because you want to send other information.



For example, you can send the content of another input that will be created later.

You shouldn't use stringify if the target browser is IE7 or lesser without adding json2.js.

+3


source


I don't think JSON.stringify does what you need. Check the behavior when working with 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 only want 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.

Very important: How to avoid JSON string containing newlines using javascript?

+1


source


Complexity. I do not know what to say.

Take the urlencode function from the function list and ditch it a bit.

<?php

$textdata = $_POST['textdata'];

///// Try without this one line and json encoding tanks
$textdata = urlencode($textdata);


/******* textarea data slides into JSON string because JSON is designed to hold urlencoded strings ******/ 

$json_string = json_encode($textdata); 


//////////// decode just for kicks and used decoded for the form

$mydata = json_decode($json_string, "true");

/// url decode
$mydata = urldecode($mydata['textdata']);

?>


<html>
<form action="" method="post">
<textarea name="textdata"><?php echo $mydata; ?></textarea>
<input type="submit">
</html>

      

The same can be done in Javascript to store textarea data in local storage. Again textarea will fail unless all unix formatting has been processed. Answer: Take urldecode / urlencode and punch it around.

I believe the server side urlencode will be a C-wrapped function that iterates over the char array after erasing, executing a piece of interpreted code.

The returned textarea will be exactly what was entered with zero chance of breaking the wyswyg editor or basic HTML5 textarea, which could use a combination of HTML / CSS, DOS, Apple and Unix depending on which text is cut / pasted.

Down voices are funny and show an obvious lack of knowledge. You only need to ask yourself if this data was the contents of a file or another array of strings, how would you pass this data in the url? JSON.stringify is ok but url encoding works best on ajax client / server.

-2


source







All Articles