Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

javascript - 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:

  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

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

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...