JSON Javascript escape

前端 未结 4 832
我在风中等你
我在风中等你 2020-12-07 02:23

So i have some of my example dynamic JSON below, what i\'m having trouble doing is escaping everything properly so that it is properly processed by JSON.parse or Jquery.pars

4条回答
  •  广开言路
    2020-12-07 02:41

    Inside JSON, quotes within strings need to be escaped with a backslash: {"key": "prop with \" quote"}.

    Inside JavaScript, quotes and backslashes within string literals need to be escaped with a backslash: "string with \\backslash and \" quote".

    If you really would need to use JSON in JS string literals (there is no reason to do that), you would need to double-escape them: json = "{\"key":\"prop with \\\" quote and \\n linebreak\"}". You haven't done so for the quotes around "Windows Phone".

    However, you must've done something wrong when dealing with such problems. Usually you get JSON strings from ajax calls and such, where you get them already as a string value. If you want to echo some sever-created JSON directly into a js script, you don't need to wrap it in a string literal - it is already [nearly] valid Object Literal syntax.

提交回复
热议问题