【发布时间】:2020-06-16 10:09:59
【问题描述】:
API 数据字段只支持 ASCII 编码——但我需要支持 Unicode(表情符号、外来字符等)
我想将用户的文本输入编码为转义的 unicode 字符串:
let textContainingUnicode = """
Let's go ???? in the ????.
And some new lines.
"""
let result = textContainingUnicode.unicodeScalars.map { $0.escaped(asASCII: true)}
.joined(separator: "")
.replacingOccurrences(
of: "\\\\u\\{(.+?(?=\\}))\\}", <- converting swift format \\u{****}
with: "\\\\U$1", <- into format python expects
options: .regularExpression)
result这里是"Let\'s go \U0001F3CA in the \U0001F30A.\n And some new lines."
并在服务器上用python解码:
codecs.decode("Let\\'s go \\U0001F3CA in the \\U0001F30A.\\n And some new lines.\n", 'unicode_escape')
但这闻起来很有趣——我真的需要在 swift 中进行如此多的字符串操作来获得转义的 unicode 吗?这些格式是否没有跨语言标准化。
【问题讨论】:
-
为什么不能直接将原始字符串发送到服务器? Unicode 本身就是“标准化格式”。
-
这是AWS的一个约束:“用户定义的元数据是一组键值对。Amazon S3以小写形式存储用户定义的元数据键。每个键值对必须符合US-ASCII当您使用 REST 和 UTF-8 时,当您使用 SOAP 或通过 POST 进行基于浏览器的上传时。”他们不再使用 SOAP 客户端,我猜我可以自己编写。 docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html