我试图显示双引号,但它显示了一个反斜杠:

"maingame": {
    "day1": {
        "text1": "Tag 1",
        "text2": "Heute startet unsere Rundreise \\\"Example text\\\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.</strong> "
    }
}

当在html中呈现时,它显示为“示例文本\”。正确的方法是什么?


当前回答

何时何地用“\\\”代替。好吧,如果你和我一样,当我发现这个帖子后意识到我在做什么时,你会觉得自己和我一样愚蠢。

如果你正在制作一个.json文本文件/流,并从那里导入数据,那么在双引号:\"之前只有一个反斜杠的主流答案就是你正在寻找的答案。

However if you're like me and you're trying to get the w3schools.com "Tryit Editor" to have a double quotes in the output of the JSON.parse(text), then the one you're looking for is the triple backslash double quotes \\\". This is because you're building your text string within an HTML <script> block, and the first double backslash inserts a single backslash into the string variable then the following backslash double quote inserts the double quote into the string so that the resulting script string contains the \" from the standard answer and the JSON parser will parse this as just the double quotes.

<script>
  var text="{";
  text += '"quip":"\\\"If nobody is listening, then you\'re likely talking to the wrong audience.\\\""';
  text += "}";
  var obj=JSON.parse(text);
</script>

+1:由于它是一个JavaScript文本字符串,双反斜杠双引号\\"也可以;因为双引号不需要在单引号字符串中转义,例如'\"'和'"'会产生相同的JS字符串。

其他回答

为了转义导致JSON数据出现问题的反斜杠,我使用了这个函数。

//escape backslash to avoid errors
var escapeJSON = function(str) {
    return str.replace(/\\/g,'\\');
};

试试这个:

"maingame": {
  "day1": {
    "text1": "Tag 1",
     "text2": "Heute startet unsere Rundreise \" Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.</strong> "
  }
}

(在引号前只有一个反斜杠(\))。

何时何地用“\\\”代替。好吧,如果你和我一样,当我发现这个帖子后意识到我在做什么时,你会觉得自己和我一样愚蠢。

如果你正在制作一个.json文本文件/流,并从那里导入数据,那么在双引号:\"之前只有一个反斜杠的主流答案就是你正在寻找的答案。

However if you're like me and you're trying to get the w3schools.com "Tryit Editor" to have a double quotes in the output of the JSON.parse(text), then the one you're looking for is the triple backslash double quotes \\\". This is because you're building your text string within an HTML <script> block, and the first double backslash inserts a single backslash into the string variable then the following backslash double quote inserts the double quote into the string so that the resulting script string contains the \" from the standard answer and the JSON parser will parse this as just the double quotes.

<script>
  var text="{";
  text += '"quip":"\\\"If nobody is listening, then you\'re likely talking to the wrong audience.\\\""';
  text += "}";
  var obj=JSON.parse(text);
</script>

+1:由于它是一个JavaScript文本字符串,双反斜杠双引号\\"也可以;因为双引号不需要在单引号字符串中转义,例如'\"'和'"'会产生相同的JS字符串。

如果你想在JSON中转义双引号,使用\\来转义。

如果你想创建以下javascript对象的json

{time: '7 "o" clock'}

那么你必须按照下面的方式写

'{"time":"7 \\"o\\" clock"}'

如果我们使用JSON.parse()来解析它

JSON.parse('{"time":"7 \\"o\\" clock"}')

结果将是

{time: "7 "o" clock"}

它显示了反斜杠因为你也在转义反斜杠。

除了双引号,如果想在JSON带引号字符串中包含反斜杠,还必须转义反斜杠。然而,如果你打算在转义序列中使用反斜杠,显然你不应该转义它。