如何使用AppleScript确保以UTF-8编码写入桌面JSON文件
用AppleScript写入UTF-8编码.json文件的正确姿势
嘿,你找对方向了!as «class utf8»确实是解决这个问题的核心——AppleScript默认用MacRoman编码写入文件,这就是你那些æøå特殊字符可能出现乱码的原因。只需要在write语句里加上这个编码指定,就能强制文件以UTF-8格式保存。
修改后的完整代码
set fileContent to "This is some text content with æøå letters" set this_data to fileContent set target_file to (((path to desktop folder) as string) & (time string of (current date)) & "_myfile.json") set append_data to true try set the target_file to the target_file as string set appleScriptfilePath to target_file as string set the open_target_file to open for access file target_file with write permission if append_data is false then set eof of the open_target_file to 0 -- 关键:添加as «class utf8»指定UTF-8编码 write this_data to the open_target_file starting at eof as «class utf8» close access the open_target_file on error try close access file target_file end try end try
几个重要细节说明
- 编码指定的作用:
as «class utf8»会让AppleScript把你的文本转换成UTF-8字节流写入文件,完美支持所有Unicode字符,包括你用到的æøå。 - JSON格式注意:既然你保存的是
.json文件,要是之后要写入真正的JSON结构(比如键值对),记得确保内容符合JSON语法,比如:set fileContent to "{\"message\": \"This is some text content with æøå letters\"}" - 错误处理的必要性:你原有的错误处理逻辑很实用,能避免因为异常情况导致文件一直处于打开状态,这个一定要保留。
另外补充下:«class utf8»默认生成的是不带BOM的UTF-8,这也是JSON文件的标准格式,完全符合行业规范,不需要额外调整。
内容的提问来源于stack exchange,提问作者Baldrian Sector
相关产品推荐
相关产品推荐

