1

I need a Classic ASP function that will take a string such as Jämshög and convert it to J\u00e4msh\u00f6gso that all the accented characters become their equivalent unicode escape codes.

I am sending this data in a JSON string to an API that requires all special characters to use unicode escape codes.

I've been searching for what seems like hours to come up with a solution and I haven't managed to come close. Any help would be greatly appreciated.

Claire_Monkey
  • 109
  • 1
  • 2
  • 13

1 Answers1

3

Take a look at the function from aspjson below. It also handles non-unicode characters that must to be escaped such as quote, tab, line-feed etc. Luckily no dependencies, so works stand-alone too.

Function jsEncode(str)
    Dim charmap(127), haystack()
    charmap(8)  = "\b"
    charmap(9)  = "\t"
    charmap(10) = "\n"
    charmap(12) = "\f"
    charmap(13) = "\r"
    charmap(34) = "\"""
    charmap(47) = "\/"
    charmap(92) = "\\"

    Dim strlen : strlen = Len(str) - 1
    ReDim haystack(strlen)

    Dim i, charcode
    For i = 0 To strlen
        haystack(i) = Mid(str, i + 1, 1)

        charcode = AscW(haystack(i)) And 65535
        If charcode < 127 Then
            If Not IsEmpty(charmap(charcode)) Then
                haystack(i) = charmap(charcode)
            ElseIf charcode < 32 Then
                haystack(i) = "\u" & Right("000" & Hex(charcode), 4)
            End If
        Else
            haystack(i) = "\u" & Right("000" & Hex(charcode), 4)
        End If
    Next

    jsEncode = Join(haystack, "")
End Function
Kul-Tigin
  • 16,728
  • 1
  • 35
  • 64
  • Thank you so much! This is exactly what I needed. – Claire_Monkey Sep 18 '17 at 08:13
  • Is there a way to do it the other way around? – hormigaz Mar 18 '20 at 12:47
  • @hormigaz The other way around (decoding / parsing) is more complicated than this. I'd take a look at other libraries **capable of parsing** JSON for ASP Classic. – Kul-Tigin Mar 18 '20 at 13:53
  • 1
    Hi @Kul-Tigin! I've found another library that works perfectly and decode unicode characters based on your locale language. Link Here --> [JSON object class 3.8.1 By RCDMK](https://github.com/rcdmk/aspJSON). – hormigaz Mar 19 '20 at 15:10