Access/VBA Library


Converts the content of a String to JSON format and returns the converted string.

Special characters as Tab, Cr, Lf, FF, \ and / are escaped and charachters with an ASCII code above 255 are converted to hexadecimal values.


StringToJSON( aString )
Name Type Description
aString String Required. VBA-string to be converted.
Return value

String : The content of aString converted to JSON-format.

Function StringToJSON(aString As String) As String
    Dim Index As Long
    Dim ch As String
    Dim code As Long
    Dim result As String
    For Index = 1 To Len(aString)
        ch = Mid(aString, Index, 1)
        code = AscW(ch)
        If code < 0 Then code = 65536 + code
        Select Case code
            Case 8: Concat result, "\b"
            Case 9: Concat result, "\t"
            Case 10: Concat result, "\n"
            Case 12: Concat result, "\f"
            Case 13: Concat result, "\r"
            Case 34: Concat result, "\" & Chr(34)
            Case 47: Concat result, "\/"
            Case 92: Concat result, "\\"
            Case 256 To 65536:
                ch = Hex(code)
                While Len(ch) < 4
                    ch = "0" & ch
                Concat result, "\u" & ch
            Case Else
                Concat result, ch
        End Select
    Next Index
    StringToJSON = result
End Function