转义非ASCII字符(或如何删除BOM表?) [英] Escaping non-ASCII characters (or how to remove the BOM?)

查看:80
本文介绍了转义非ASCII字符(或如何删除BOM表?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从Access记录集创建一个ANSI文本文件,该记录集输出到JSON和YAML.我可以写文件,但是输出是带有原始字符的,我需要对它们进行转义.例如,umlaut-O(ö)应为"\ u00f6".

I need to create an ANSI text file from an Access recordset that outputs to JSON and YAML. I can write the file, but the output is coming out with the original characters, and I need to escape them. For example, an umlaut-O (ö) should be "\u00f6".

我认为将文件编码为UTF-8是可以的,但是没有用.但是,再次查看文件编码后,如果您编写不带BOM的UTF-8",则一切正常.

I thought encoding the file as UTF-8 would work, but it doesn't. However, having looked at the file coding again, if you write "UTF-8 without BOM" then everything works.

有人知道怎么做

a)将文本以UTF-8格式写出,而无需BOM,或者 b)用ANSI编写但转义非ASCII字符?

a) Write text out as UTF-8 without BOM, or b) Write in ANSI but escaping the non-ASCII characters?

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

推荐答案

...好的....我找到了一些有关如何删除BOM的示例代码.我本来以为实际上在最初编写文本时可以做得更优雅.没关系.以下代码删除了BOM.

... ok .... i found some example code on how to remove the BOM. I would have thought it would be possible to do this more elegantly when actually writing the text in the first place. Never mind. The following code removes the BOM.

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

(This was originally posted by Simon Pedersen at 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

这可能对其他人有用.

这篇关于转义非ASCII字符(或如何删除BOM表?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆