Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

  1. 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.

  2. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
488 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...