Javascript textarea line break into database for result as JSON String - javascript

I want to save the textarea line breaks to the database (Mongoose - MongoDB latest). For frontend I'm working with iQuery or simple Javascript.
I'm getting currently the following error message from json parse
VM533:1 Uncaught SyntaxError: Unexpected token
in JSON at position 207
at JSON.parse ()
at profil:390
Json line which created this error
"My name is example
My name is example"}
In my Database is no \n or other html codes saved.
I need to save the textarea line breaks into the database for the result json string with json parse, has anyone a workaround?
UPDATE1
The JSON Result is only a snipped. Here is the full json result it's works perfect if the profile_description has NO line breaks
{"_id":"XYZ","business_id":"7XYZ","banner_url":"XYZ","__v":0,"profile_description":"My name is example
My name is example"}

Json line which created this error
"My name is example
My name is example"}
That is not valid JSON to begin with.
In JavaScript, a text literal delimited by single or double quotes, can not contain an actual line break. It would either need an \ at the end of every line, or the line breaks would need to be replaced with the characters \n inside the text literal.
It is important to always properly differentiate between data, and code.
When you read the field value using $(this).val(), the result is data. In there, you have an actual line break, hexadecimal byte value 0A.
But JSON is code, it needs to get parsed. So it has to follow the basic syntax rules for text literals, that JavaScript imposes.
So those line breaks would need to be replaced by the characters \n, which can be done simply by
someVariableContainingText = someVariableContainingText.replace(/\n/g, "\\n")
That would get you "My name is example\nMy name is example" here, and that now is a valid JS text literal. As soon as your JSON contains that, instead of an actual line break, it can be parsed properly.

Related

Angular Markdown Parsing "\n" Newline Characters Issue

I've created a blog where markdown is returned as a string from my backend, however when I return a string with the correct newline characters it does not behave as expected.
I am using ngx-markdown to handle parsing of markdown characters, and using the ngPreserveWhitespaces attribute to ensure this should be functioning as expected.
Example:
// Example #1 Returned String
"## This is a subheader\n This is a sentence"
// Output
<h2>This is a subheader\n This is a sentence</h2>
It displays it as a single line with the newline character physically rendered as text, as above.
However within any of my Angular components I can literally write this same string as a property on the component and return it, and it renders correctly like so:
// Example #2 Hard Coded String
public correct: string = "## This is a subheader\n This is a sentence";
// Output
<h2>This is a subheader</h2>
<p>This is a sentence</p>
As mentioned, the markdown parser I am using is implemented as such:
<markdown ngPreserveWhitespaces>{{content}}</markdown>
I have also attempted to do this by setting ngPreserveWhitespaces within the main/tsconfig files. However I do not believe this is what the issue is, as I can (natively in JS) console.log both my returned string (#1) and the hard coded string (#2) and even my damn logs display differently (with the latter formatting correctly and the former just stringifying the output).
I have attempted:
JSON stringify/parsing the data in multiple ways (as well as without)
I have attempted using regex to manually replace characters
I have attempted to just manually use <br />
I have tried everything outlined here regarding this markdown parser handling whitespace (which I do not believe is the issue)
Nothing appears to appease the newline gods.
Solution
Okay so I've found my solution to this, I am now storing my markdown string as such:
"## This is a subheader\n This is a sentence"
This difference here is the interface I'm storing this within (a Mongo db) puts the speechmarks around string values already, so it now actually looks like this:
""## This is a subheader\n This is a sentence""
Which is more a weird thing with MongoDB Compass than with what I was attempting.
From this, I am able to JSON.parse the value correctly (previously it was attempting to do so with a string that wasn't valid JSON as it wasn't enclosed in double speechmarks).
I am now handling this in an extension of a Property class I have for each of these called HtmlProperty which when instantiated, parses the value correctly.

Weird symbol in string breaks JSON.parse, but seems to be undetectable?

The description field is a text area field, somehow a user ended up with some strange little symbol in it. (see image)
When I grab this from the server, I assemble my data from the objects I grab, which includes the description on this object, and turn it into JSON string, and send it to my javascript.
From javascript, I JSON.parse it. But that weird little symbol causes the parse to fail. But, when you look at it, there is no character there or anything, yet it throws an undefined character in JSON.parse.
My response from the server has the description like this:
"blahblahtesttext\r\nslkdjf",
There is nothing but the expected \r\n......
But it has an unexpected token where that symbol is.
{"value":"blah blah test text//Symbol should be here, but there is nothing and it forces it to the next line
\r\nslkdjf","fieldType":"TEXTAREA","field":"Description"}
Where that symbol forces the string to the next line, which causes the issue.
Because I can't see what the actual character is... I do not know how to handle this.
Is there something that can strip out invalid characters in a JSON string so the parse works? I don't want to just try/catch this as it would toss out everything, I just want that weird invalid symbol to be stripped out.
Or is there a way to see what the actual character is that JSON.parse does not like?

 <-- here is that symbol for copy pasting into a string if you want to try parsing it.
EDIT:
I found that it was doing this in Notepad++
Where you can see that where the line separator was, it is placing actual carriage return and line feed there, breaking the string. It already has \r\n\r\n for the two returns that were placed in the actual text area after that line separator character.
But still unsure of how to deal with this, as that carriage return and line feed do not appear in the string as '\n\r', there is no character representation of them, but instead it actually puts a return there and breaks the string.
NEW EDIT:
Finally found something to get this working. I couldn't do a replace on that line separator character. When I pulled it from my database, it came through as a hidden carriage return. When you manually pressed 'Enter' in the text area, the string I got from the database would actually put a '\r\n' there. But the line separator did not.
So, I added these three lines before parsing to ensure I was escaping any invalid new lines/carriage returns.
result = result.replace(/\r\n/g, '\\r\\n');
result = result.replace(/\r/g, '\\r');
result = result.replace(/\n/g, '\\n');
The '\r\n' that were actually in the string would correctly be escaped already, which tripped me up because I didn't have to worry about escaping those until someone tried introducing this line separator....
As Xufox says, that appears to be U+2028. JSON.parse shouldn't fail on it since U+2028 doesn't require escaping in JSON; Chrome's doesn't, but that's probably because it's implementing this stage 4 proposal Xufox pointed out:
const o = {prop: "testing\u2028one two three"};
console.log(JSON.parse(JSON.stringify(o)));
If you need to work around a JSON.parse implementation that doesn't handle it, you could do this:
str = str.replace(/\u2028/g, "\\u2028");
...before running JSON.parse on str.

JSP attribute JSON object is dropping escape characters in Javascript

I have a server-side controller which is adding an attribute which is a Java object converted to JSON using Jackson:
ObjectMapper mapper = new ObjectMapper();
model.addAttribute("commentObj", mapper.writeValueAsString(commentObject);
My commentObject has a field "comments" which contains quotation marks (") that JSON needs to escape. When I do a simple print-out from the JSP of the commentObject, everything looks good:
[{"commentId":123,"comments": "this \"test\" is here"}]
As you see, the quotes get escaped properly (\").
My problem comes with the javascript on this page that also needs to access this object. So when I run the following:
<script>
var test = ${commentObj};
</script>
If I take a look at the 'test' var, the comments field now reads as follows:
"this "test" is here"
vs.
"this \"test\" is here"
This causes a problem because JSON.parse() will throw an error on 'test' because it is not properly formed JSON anymore.
So my question is, how do I manage to get my commentObj into a javascript object while keeping the escape characters so that I can JSON.parse it properly?
Sorry, written at the end of a long day while sick and only just realized now that the 'test' var ends up being a fully formed JS object. So I am able to use that.
That said, I still have the question of how that is happening? It seems to me that it should be coming in as a JSON string that I need to call JSON.parse on. Anyone have an explanation?

Special Characters in JSON return value throwing errors

I have some code using datatables and one of the fields that is returned is a string value and lately people have been pasting values in this field from emails that contain some special characters like those found in MS-Word smart quotes. When it tries to display I get an error.
If I copy / paste the text into notepad++ I can see some strange symbols. Once I remove them the error goes away.
Is there away to some how strip all special characters from my text with a function call in Javascript?
Does this woks for you:
myStr=myStr.replace(/[^\w\s]/gi, '')
You can add more characters to this "white list" for example:
myStr=myStr.replace(/[^\w\s,\/#!$%\^&\*;:]/gi, '');

JSON Parse with square brackets inside data

I am trying to parse a JSON string which contains square brackets inside the string.
For example
"[[\"hello\", \"i\", \"like [cows]\"], [\"what\", \"about [you]?\"]]"
It shows an error while parsing:
Uncaught SyntaxError: Unexpected token [
How can I parse the string anyway while leaving the brackets as they are?
I found the problem. I needed to use addslashes() around the strings in the PHP code which serves the code. There was a part of a string containing [C:\].
I see in your later comments that you're creating this JSON string within PHP. You should encode the JSON data within PHP using json_encode, as shown here:
http://www.dyn-web.com/tutorials/php-js/json/array.php
It should then come out in a format that you can JSON.parse.

Categories

Resources