JSON Parse Unexpected token h caused quotes inside string value - javascript

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.

Related

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.

remove '\' from string api response aws lambda

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.

JSON.parse get "Uncaught SyntaxError: Unexpected token h"

I get the syntax error when I try to pass the following string:
JSON.parse("[{\"Date\": \"4/4/2016 4:15:19 PM\", \"Message\":\"<h3>New
Message</h3> Generated at 4/4/2016 4:15:19 PM.<br/><br/>Heavy Responsive
URL: <a href=\"https://performingarts.withgoogle.com/en_us\" ></a><br/><br/>
<img src=\"https://s-media-cache-ak0.pinimg.com/236x/06/bd/ac/06bdacc904c12abdce3381ba1404fd7e.jpg\" /> \"} ]");
I know that the error come from the link when I use double quote.
If I use single quote then no issue, but the data is getting from server side, I got no control over what going to pass in so I can only control on my side.
From what I read from the internet so far, I tried the following:
Use JSON.stringify first, then only use JSON.parse. I can parse
with no issue but problem occur when I try to loop the data. Instead
of looping it as JSON, the loop take the data as string and loop
every single text.
Escape every double quote which I'm currently doing, but it's not
working as shown above. But if I replace every double quote to
literal, I'm afraid some of the message that suppose to be double
quote will turn into literal as well, which will result in weird
looking message.
Please advice what other alternative I have to solve this.
You have JSON embedded in a JavaScript string literal.
" and \ are special characters in JSON and are also special characters in a JavaScript string literal.
href=\"https: escapes the " in the JavaScript string literal. It then becomes a " in the JSON. That causes an error.
When you want the " as data in the JSON you must:
Escape the " for JavaScript (as you are doing already)
Escape the " for JSON by adding a \.
Escape the \ for JavaScript
href=\\\"https:

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コメ欄と陰謀論が嫌いです。"}')

Categories

Resources