javascript - Why does this json string fails to parse -


Maybe I can not see it now, but why is it unable to parse Jason string? (Since its validity)

  var content = $ .parseJSON ('{"foobar": "halo \" tow "}');   < p>  

Because you are creating JSON in that string literally, you \ needs to be avoided:

  var content = $ .parseJSON ('{"foobar": "halo \\" tow "}'); Console.log (content);   

Explanation:

In JSON, " character \ avoids the use of characters The following are completely valid JSON:

  {"foobar": "hallo \" tow "}   

Now, in your example, The values ​​within a JavaScript string were created:

  '{"foobar": "hello \" tow "}'   

This is a subtle Issue due to which the fact is that the javascript string also escape " with the letter \ characters Student. That is, the following string is literally:

  ''   

... assumes the value:

  "< Now, after re-implementing your example, we find that this string is really:  
  '{"foobar": "hello \" tow "} ''   

... really values:

  {" foobar ":" hello "to"}   

As you can see, we've lost our \ . Fortunately, this task is easy, as \ is also in the JavaScript string \ characters Now, the modified string is literally:

  '{"foobar": "hello \\" tow "}'   

string is parsed as holding value:

  {"foobar": "hallo \" tow "}   

... which can then be parsed as properly formatted JSON

You do not have this problem while reading from a textarea or as a result of an AJAX request That JSON value is defined by string Being o. Extra \ is only required due to string literal syntax, and to avoid the competition that is spoken before " first (okay, there really is not a competition) Going ... string literally always wins).

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -