Reputation: 65
I'm generating a JSON file using VB6 and one of my strings has a double quote in between. I have used the double quote escape character but now the escape character is also printing in the string, even though the JSON is successful when I put the file in JSON formatter.
The string is:
"productName":"16X12 / 46/4X46 63" DRILL"
This string have a double quote in it when I use escape character and check it the JSON formatter , the JSON is successful but product name string becomes
"productName":"16X12 / 46/4X46 63\"DRILL"
as u can see the escape character is printing in the string before the double quote, How can I escape the double quote without printing the escape character.
I have tried with \ and \\ but every \ get prints.
Upvotes: 0
Views: 1359
Reputation: 11991
You need a proper JSON string escaping implementation, e.g. try this
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
This takes care of "
and \
in strings as well as vbCrLf
and other special symbols (charcode < 32). This handles unicode characters too (charcode > 256).
Btw, you'll have to escape all user-supplied strings (either in keys or values) to prevent producing invalid JSON in all cases.
Upvotes: 3