JSON中如何转义字符串中的双引号(转载)

问:


 

I'm trying to show double quotes but it shows one of the backslashes:

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

When rendering in the html it shows as \"Example text\". What is the correct way?

 

 

答:


 

Try this:

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

(just one backslash (\) in front of quotes).

 

 

JSON字符串中的转义字符和C#一样,都是用反斜线"\"开头的,例如:

\b  Backspace (ascii code 08)
\f  Form feed (ascii code 0C)
\n  New line
\r  Carriage return
\t  Tab
\"  Double quote
\\  Backslash character

 

 

参考文献:

How to escape double quotes in JSON

How to escape special characters in building a JSON string?

 

转载于:https://www.cnblogs.com/OpenCoder/p/10873936.html

### 如何在 JSON 字符串中正确转义多层嵌套的双引号 JSON 中的字符串需要用双引号 (`"`) 来界定,并且需要对某些特殊字符进行转义,包括但不限于: - 反斜杠 `"\\"` - 控制字符如换行符 (`\n`) 和制表符 (`\t`) 当处理多层嵌套的 JSON 数据时,每一层中的双引号都需要按照上述规则进行适当转义。 #### 示例:单层嵌套 假设有一个简单的 JSON 对象,其中包含一个带有双引号字符串字段: ```json { "message": "He said \"Hello World!\"" } ``` 这里,内部的双引号被成功转义为 `\"`[^1]。 #### 多层嵌套示例 考虑更复杂的场景——一个多层嵌套的对象,其中一个属性值也是一个 JSON 字符串: ```json { "outerMessage": "{\"innerMessage\": \"This is a nested message with \\\"another level\\\" of nesting.\"}" } ``` 在这个例子中: - 第一层的双引号保持不变。 - 内部 JSON 的最外层双引号转义成 `\"`。 - 更深层次内的双引号进一步转义为 `\\\"`,以此类推。 为了更好地理解这一点,可以将其拆解如下: - **原始内层消息**: This is a nested message with "another level" of nesting. - **第一次转义后的内层消息 (作为外部对象的一部分)**: `{\"innerMessage\": \"This is a nested message with \\\"another level\\\" of nesting.\"}` - **最终完整的 JSON 结构**: ```json { "outerMessage": "{\"innerMessage\": \"This is a nested message with \\\"another level\\\" of nesting.\"}" } ``` 这种模式可以根据实际需求扩展到更多层次。每增加一个新的嵌套级别,就需要额外的一次反斜杠转义操作。 #### 使用编程语言实现自动转义 许多现代编程语言提供了内置函数来帮助处理这些复杂情况下的字符串转义问题。例如,在 Python 中可以通过 `json.dumps()` 方法轻松完成这一过程而不必手动书写繁琐的转义序列。 ```python import json data = { 'outerMessage': json.dumps({ 'innerMessage': 'This is a nested message with "another level" of nesting.' }) } print(json.dumps(data)) ``` 这段代码会自动生成正确的多重转义版本的 JSON 输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值