转义非ASCII字符(或如何删除BOM?)

alj*_*alj 5 ms-access encoding vba

我需要从Access记录集创建一个ANSI文本文件,输出到JSON和YAML.我可以写文件,但输出是原始字符,我需要逃避它们.例如,变音符号O(ö)应为"\ u00f6".

我认为将文件编码为UTF-8会起作用,但事实并非如此.但是,再次查看文件编码,如果你写"没有BOM的UTF-8"那么一切正常.

有谁知道怎么做

a)在没有BOM的情况下将文本写为UTF-8,或b)用ANSI写入但是转义非ASCII字符?

Public Sub testoutput()

Set db = CurrentDb()

str_filename = "anothertest.json"
MyFile = CurrentProject.Path & "\" & str_filename
str_temp = "Hello world here is an ö"

fnum = FreeFile

Open MyFile For Output As fnum
Print #fnum, str_temp
Close #fnum

End Sub
Run Code Online (Sandbox Code Playgroud)

alj*_*alj 7

...好吧....我找到了一些关于如何删除BOM的示例代码.我本以为在实际编写文本时可以更优雅地做到这一点.没关系.以下代码删除了BOM.

(最初由Simon Pedersen在http://www.imagemagick.org/discourse-server/viewtopic.php?f=8&t=12705上发布)

' Removes the Byte Order Mark - BOM from a text file with UTF-8 encoding
' The BOM defines that the file was stored with an UTF-8 encoding.

Public Function RemoveBOM(filePath)

    ' Create a reader and a writer
            Dim writer, reader, fileSize
            Set writer = CreateObject("Adodb.Stream")
            Set reader = CreateObject("Adodb.Stream")

    ' Load from the text file we just wrote
            reader.Open
            reader.LoadFromFile filePath

    ' Copy all data from reader to writer, except the BOM
            writer.Mode = 3
            writer.Type = 1
            writer.Open
            reader.Position = 5
            reader.CopyTo writer, -1

    ' Overwrite file
            writer.SaveToFile filePath, 2

    ' Return file name
            RemoveBOM = filePath

    ' Kill objects
            Set writer = Nothing
            Set reader = Nothing
    End Function
Run Code Online (Sandbox Code Playgroud)

它可能对其他人有用.