Koo SengSeng Koo SengSeng - 23 days ago 19
Javascript Question

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
    first, then only use
    . 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.

Answer Source

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