JSON 字符串中打印双引号的转义字符
JSON Escape character of double quote prints in the string
我正在使用 VB6 生成一个 JSON 文件,我的一个字符串之间有一个双引号。我使用了双引号转义字符,但现在转义字符也在字符串中打印,即使当我将文件放入 JSON 格式化程序时 JSON 成功。
字符串是:
"productName":"16X12 / 46/4X46 63" DRILL"
当我使用转义字符并检查 JSON 格式化程序时,该字符串中有双引号,JSON 成功但产品名称字符串变为
"productName":"16X12 / 46/4X46 63\"DRILL"
如您所见,转义字符打印在双引号之前的字符串中,如何在不打印转义字符的情况下转义双引号。
我尝试过使用 \ 和 \\,但每次 \ get 都会打印出来。
您需要一个适当的 JSON 字符串转义实现,例如试试这个
Private Function JsonEscape(sText As String) As String
Const STR_CODES As String = "\u0000|\u0001|\u0002|\u0003|\u0004|\u0005|\u0006|\u0007|\b|\t|\n|\u000B|\f|\r|\u000E|\u000F|\u0010|\u0011|\u0012|\u0013|\u0014|\u0015|\u0016|\u0017|\u0018|\u0019|\u001A|\u001B|\u001C|\u001D|\u001E|\u001F"
Static vTranscode As Variant
Dim lIdx As Long
Dim lAsc As Long
If IsEmpty(vTranscode) Then
vTranscode = Split(STR_CODES, "|")
End If
For lIdx = 1 To Len(sText)
lAsc = AscW(Mid$(sText, lIdx, 1))
If lAsc = 92 Or lAsc = 34 Then '--- \ and "
JsonEscape = JsonEscape & "\" & ChrW$(lAsc)
ElseIf lAsc >= 32 And lAsc < 256 Then
JsonEscape = JsonEscape & ChrW$(lAsc)
ElseIf lAsc >= 0 And lAsc < 32 Then
JsonEscape = JsonEscape & vTranscode(lAsc)
ElseIf Asc(Mid$(sText, lIdx, 1)) <> 63 Or Mid$(sText, lIdx, 1) = "?" Then '--- ?
JsonEscape = JsonEscape & ChrW$(AscW(Mid$(sText, lIdx, 1)))
Else
JsonEscape = JsonEscape & "\u" & Right$("0000" & Hex$(lAsc), 4)
End If
Next
End Function
这会处理字符串中的 "
和 \
以及 vbCrLf
和其他特殊符号 (charcode < 32)。这也处理 unicode 字符 (charcode > 256)。
顺便说一句,您必须转义所有用户提供的字符串(无论是键还是值),以防止在所有情况下都产生无效的 JSON。
我正在使用 VB6 生成一个 JSON 文件,我的一个字符串之间有一个双引号。我使用了双引号转义字符,但现在转义字符也在字符串中打印,即使当我将文件放入 JSON 格式化程序时 JSON 成功。
字符串是:
"productName":"16X12 / 46/4X46 63" DRILL"
当我使用转义字符并检查 JSON 格式化程序时,该字符串中有双引号,JSON 成功但产品名称字符串变为
"productName":"16X12 / 46/4X46 63\"DRILL"
如您所见,转义字符打印在双引号之前的字符串中,如何在不打印转义字符的情况下转义双引号。
我尝试过使用 \ 和 \\,但每次 \ get 都会打印出来。
您需要一个适当的 JSON 字符串转义实现,例如试试这个
Private Function JsonEscape(sText As String) As String
Const STR_CODES As String = "\u0000|\u0001|\u0002|\u0003|\u0004|\u0005|\u0006|\u0007|\b|\t|\n|\u000B|\f|\r|\u000E|\u000F|\u0010|\u0011|\u0012|\u0013|\u0014|\u0015|\u0016|\u0017|\u0018|\u0019|\u001A|\u001B|\u001C|\u001D|\u001E|\u001F"
Static vTranscode As Variant
Dim lIdx As Long
Dim lAsc As Long
If IsEmpty(vTranscode) Then
vTranscode = Split(STR_CODES, "|")
End If
For lIdx = 1 To Len(sText)
lAsc = AscW(Mid$(sText, lIdx, 1))
If lAsc = 92 Or lAsc = 34 Then '--- \ and "
JsonEscape = JsonEscape & "\" & ChrW$(lAsc)
ElseIf lAsc >= 32 And lAsc < 256 Then
JsonEscape = JsonEscape & ChrW$(lAsc)
ElseIf lAsc >= 0 And lAsc < 32 Then
JsonEscape = JsonEscape & vTranscode(lAsc)
ElseIf Asc(Mid$(sText, lIdx, 1)) <> 63 Or Mid$(sText, lIdx, 1) = "?" Then '--- ?
JsonEscape = JsonEscape & ChrW$(AscW(Mid$(sText, lIdx, 1)))
Else
JsonEscape = JsonEscape & "\u" & Right$("0000" & Hex$(lAsc), 4)
End If
Next
End Function
这会处理字符串中的 "
和 \
以及 vbCrLf
和其他特殊符号 (charcode < 32)。这也处理 unicode 字符 (charcode > 256)。
顺便说一句,您必须转义所有用户提供的字符串(无论是键还是值),以防止在所有情况下都产生无效的 JSON。