remove '\' from string api response aws lambda - javascript

I am have AWS Lambda function where I am sending a string as my final response
let abc= `"phone_exist":"0","calls":"0","lastaction":"0"`
callback(null,abc);
Output: "\"phone_exist\":\"0\",\"calls\":\"0\",\"lastaction\":\"0\""
here I am unable to understand why "\" has been appended in my string.
Can anyone explain me the reason behind this?
Is their a way using which '\' can be removed so I can get in following form
"phone_exist"="1","calls"="2","lastaction"="3"

You are returning a string, not an object, so Lambda is encoding your string as JSON. What you actually want is most likely this:
let abc = { "phone_exist":"0","calls":"0","lastaction":"0" };
callback(null,abc);
Since those are numbers, you may not want to quote them.

The backslash(\) is an escape character for the special character Double Quote(").
Remove them(") from your original string...
Or ignore them as they are just escape characters.

Related

JSON Parse Unexpected token h caused quotes inside string value

I have a JSON string that I got from the table, here's my JSON
{"subtitle":"Information","desc":"Hi, Welcome.\\n <br><br>\\n You can access our website here.\\n <br><br>\\n Dont forget, cost: only $2! \\n <br>\\n <br>\\n <br>\\n <br>\\n Thankyou,<br>\\n Regards"}
when I'm trying to do json.parse() but I got an error
SyntaxError: Unexpected token h in JSON at position 154.
I thought it caused because of the quotes " in URL or colon :.
How do I can pass them to JSON?
Update
Here's how I got the data:
var body_inbox = {};
body_inbox.subtitle = 'Information';
body_inbox.desc = `Hi, Welcome.
<br><br>
You can access our website here.
<br><br>
Dont forget, cost: only $2!
<br>
<br>
<br>
<br>
Thankyou,<br>
Regards`;
body_inbox = JSON.stringify(body_inbox);
I am confused, I found many data in table that data has double backslash in newline \\n and in url here. I just try create new data with JSON.stringify and the result is \n and here. Why does this happen?
Note
Sorry, there's a misleading the earlier data is typo.
It should be <a href=\\"https://test.com\\"> not <a href="\\https://test.com\\">
The double backslashes should be single backslashes. A single backslash escapes the following character, so what you’re doing with the double is escaping the second backslash. It chokes on the href because the quote that follows ends the string, after which the parser hits the ‘h’ in the url as a raw character.
{ message: "...our website here" }
// ^ parser thinks the string ends here
// and doesn't know what to make of
// https://...
My guess is that the data got escaped twice by two different processes (or the same process run twice).
Hypothetical example: The data gets created, and on the way into the database it gets escaped. So now all quotes are preceded by a backslash. Then an edit is made to the data and the record is updated in the database, and the escaping gets run again. But the input string already has backslashes in it from the first time, and because backslashes themselves are special and need to be escaped, when the string gets escaped (again) on its way back to the database you end up with double backslashes.
You can see this kind of thing by escaping a string twice in the console. (This isn't doing backslashes, but it's demonstrative of the problem):
const input = '"This string is quoted."';
const once = encodeURI(input);
// encodes the quotes as '%22'
// "%22This%20string%20is%20quoted.%22"
const twice = encodeURI(once);
// encodes the '%' in '%22' as '%25', and you end up with `%2522`
// "%2522This%2520string%2520is%2520quoted.%2522"
Double quotes in json (in value) only require one forward slash(\).
So your json should be
{"subtitle":"Information","desc":"Hi, Welcome.\\n <br><br>\\n You can access our website here.\\n <br><br>\\n Dont forget, cost: only $2! \\n <br>\\n <br>\\n <br>\\n <br>\\n Thankyou,<br>\\n Regards"}
Use the template string to save data.
const json = `{"subtitle":"Information","desc":"Hi, Welcome.\\n<br><br>\\nYou can access our website here.\\n<br><br>\\nDont forget, cost: only $2!\\n<br>\\n<br>\\n<br>\\n<br>\\n Thankyou,<br>\\n Regards"}`
console.log(JSON.parse(json))
(Posted an answer from the question author to move it to the answer space).
Thank you so much for all the answers. It's helped to figure out that the parse failed caused by double backslash that escape the second backslash not the double quotes ".
The data has double backslash because of this is data from cloned database, I thought it happen during conversion to SQL file.

Only one backslash in javascript

I know that backslash is escape character in js. And to display one backslash, I need to write two.
But I am having express server that send request to database and here I need to add only one backslash. SO if filter contains two backslashes, replace it only with one. How to write it?
filter.replace("\\", String.fromCharCode(92)); //do two not one
filter.replace("\\", "\"); //doesn't work, syntax error
example
"aaaa\\aaaa" - > "aaaa\aaaa"
Another ideas?
---UPADTE---
The string that is send to database contains two backslashes but js GUI shows only one (of course).
How to write it?
You said it yourself:
to display one backslash, I need to write two.
So, if you have two in the string to start with, then you need to replace two (type four) with one (type two).
var filter = "This string has a double slash in it: \\\\";
console.log(`The original string: ${filter}`);
filter = filter.replace("\\\\", "\\");
console.log(`The filtered string: ${filter}`);
Quentin answered your question, but another way to think about it is that two backslashes written into a sting will resolve to a single backslash as soon as you do anything with it.
For example:
Console.Log("\");
//Returns Error
Console.Log("\\");
//Returns: \
var i = "this is a backslash \\"
//i now contains only one backslash
Console.Log(i);
//Returns: this is a backslash \
Edit:
Since you clarified that it's after this in the querying that it gets messed up, you could try making sure you've assigned it to a variable and then passed it to the query.
i = "A string containing backslashes \\"
sql.Query(i);
Edit 2:
Oh, I just got it, you're trying to escape colons ':' which is already handled in JS. So if the query isn't parsing your escape characters than just \: should be perfectly valid.

How to split a string in javascript by special char \

I believe that this is simple and I'm missing something. I want to split a physical path in windows with javascript. So I try with String#split function, but my result was inespected.
For this string
"C:\CLC\VIDA\Web\_REPOSITORIO\Colectivos\ReembolsosWeb\TMP_011906169_01_01.pdf"
I'm getting this result
var test = "C:\CLC\VIDA\Web\_REPOSITORIO\Colectivos\ReembolsosWeb\TMP_011906169_01_01.pdf";
test.split("\"); //throws error
test.split("\\"); //result in -> ["C:CLCVIDAWeb_REPOSITORIOColectivosReembolsosWebTMP_011906169_01_01.pdf"]
test.split(/\\/); // -> the regex is the same as above
One last thing, in my test, I found that to get the result that I want I could do it like this
var test2 = "C:\\CLC\\VIDA\\Web\\_REPOSITORIO\\Colectivos\\ReembolsosWeb\\TMP_011906169_01_01.pdf"
test2.split("\\"); // -> ["C:", "CLC", "VIDA", "Web", "_REPOSITORIO", "Colectivos", "ReembolsosWeb", "TMP_011906169_01_01.pdf"]
So my question is, how can I split the string from test var to get the array from the last case?
Strings in javascript support escape sequences via the backslash (\). For example if you need a tab in your string you can add a \t anywhere in your string and it will be replaced with a tab, a \n will be replaced with a new line.
The backslashes in test are either converted to their respective characters or dropped because they are invalid escape sequences.
To get around this you can escape one backslash with another to get a single normal backslash. The downside is that this cannot be done in javascript. Generally I paste my string in to notepad/N++/Code/Sublime and replace all \ with \\
Since you are hard coding the string you need to escape all backslashes. After that you can use test.split("\\") which, itself contains an escaped backslash.
So, as far as Javascript is concerned, your code looks like this.
var test = "C:CLCVIDAWeb_REPOSITORIOColectivosReembolsosWebTMP_011906169_01_01.pdf";
To make javascript see the string correctly you need to make it look like this...
var test = "C:\\CLC\\VIDA\\Web\\_REPOSITORIO\\Colectivos\\ReembolsosWeb\\TMP_011906169_01_01.pdf";
Firstly, note that when you have a single backslash in a string, it is used for escaping the next character. It is just ignored if there is no special character next to it to escape.
Now, just have a look at your string :
var test = "C:\CLC\VIDA\Web\_REPOSITORIO\Colectivos\ReembolsosWeb\TMP_011906169_01_01.pdf"
Don't you think all of your single backslashes will be ignored here?
So, the solution is simple, what you have already tried successfully. To escape all your backslashes with another backslash.
var test2 = "C:\\CLC\\VIDA\\Web\\_REPOSITORIO\\Colectivos\\ReembolsosWeb\\TMP_011906169_01_01.pdf"
test2.split("\\"); // -> ["C:", "CLC", "VIDA", "Web", "_REPOSITORIO", "Colectivos", "ReembolsosWeb", "TMP_011906169_01_01.pdf"]
But, are you worried about any dynamic data which has such backslash? (For example, coming from a text input or a file input.) Don't think about escaping the backslash inside it. Because you don't need to do that! It's already a well formatted string for you, which you can use as it is. You need to escape only when you are hard coding the string yourself.

JS - JSON.parse - preserve special characters

I'm running a NodeJS app that gets certain posts from an API.
When trying to JSON.parse with special characters in, the JSON.parse would fail.
Special characters can be just any other language, emojis etc.
Parsing works fine when posts don't have special characters.
I need to preserve all of the text, I can't just ignore those characters since I need to handle every possible language.
I'm getting the following error:
"Unexpected token �"
Example of a text i'm supposed to be able to handle:
"summary": "★リプライは殆ど見てません★ Tokyo-based E-J translator. ここは流れてくるニュースの自分用記録でRT&メモと他人の言葉の引用、ブログのフィード。ここで意見を述べることはしません。「交流」もしません。関心領域は匦"�アイルランドと英国(他は専門外)※Togetterコメ欄と陰謀論が嫌いです。"
How can I properly parse such a text?
Thanks
You have misdiagnosed your problem, it has nothing to do with that character.
Your code contains an unescaped " immediately before the special character you think is causing the problem. The early " is prematurely terminating the string.
If you insert a backslash to escape the ", your string can be parsed as JSON just fine:
x = '{"summary": "★リプライは殆ど見てません★ Tokyo-based E-J translator. ここは流れてくるニュースの自分用記録でRT&メモと他人の言葉の引用、ブログのフィード。ここで意見を述べることはしません。「交流」もしません。関心領域は匦\\"�アイルランドと英国(他は専門外)※Togetterコメ欄と陰謀論が嫌いです。"}';
console.log(JSON.parse(x));
You need to pass a string not as an object.
Example
JSON.parse('{"summary" : "a"}');
In your case it should be like this
JSON.parse(
'{"summary" : "★リプライは殆ど見てません★ Tokyo-based E-J translator. ここは流れてくるニュースの自分用記録でRT&メモと他人の言葉の引用、ブログのフィード。ここで意見を述べることはしません。「交流」もしません。関心領域は匦�アイルランドと英国(他は専門外)※Togetterコメ欄と陰謀論が嫌いです。"}')

Why are endline characters illegal in HTML string sent over ajax?

Within HTML, it is okay to have endline characters. But when I try to send HTML strings that have endline characters over AJAX to have them operated with JavaScript/jQuery, it returns an error that says that endline characters are illegal. For example, if I have a Ruby string:
"<div>Hello</div>"
and jsonify it with Ruby by to_json, and send it over ajax, parse it within JavaScript by JSON.parse, and insert that in jQuery like:
$('body').append('<div>Hello</div>');
then it does not return an error, but if I do a similar thing with a string like
"<div>Hello\n</div>"
it returns an error. Why are they legal in HTML and illegal in AJAX? Are there any other differences between a legal HTML string loaded as a page and legal HTML string sent over ajax?
string literals can contain line breaks, they just need to be escaped with a backslash like so:
var string = "hello\
world!";
However, this does not create a line break in the string, as it must be an explicit \n escape sequence. This would technically become helloworld. Doing
var string = "hello"
+ "world"
would be much cleaner
Specify the type of the ajax call as 'html'. Jquery will try to infer the type when parsing the response.
If the response is json, newlines should be escaped.
I'd recommend using a library to serialize json. You're unlikely to handle all the edge cases if you roll your own.
Strings in JavaScript MUST appear on a single line, with the exception of escaping that line:
var str = "abc \
def";
However note that the newline is escaped and will not appear in the string itself.
The best option is \n, but note that if it is already going through something that parses \n then you will need to double-escape it as \\n.
Seeing how you're already escaping the JSON properly by using to_json in Ruby, I do believe the bug is in jQuery; when there are newlines in the string it has trouble determining whether you meant to create a single element or a document fragment. This would work just fine:
var str = "<div>Hello\n</div>";
var wrapper = document.createElement('div');
wrapper.innerHTML = str;
$('body').append(wrapper);
Demo

Categories

Resources