Search code examples
applescript

How to write file as UTF-8 with AppleScript


I'm trying to write some text from an AppleScript as .json to a file on desktop. However I can't figure out how to make sure it writes as UTF-8.

My current code looks like this:

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
   write this_data to the open_target_file starting at eof
   close access the open_target_file
on error
   try
       close access file target_file
   end try
end try

I see people referencing "as «class utf8»", but I can't figure out how to integrate it into my code.

What's the best way of making sure it gets saved as UTF-8?


Solution

  • The people are right, just add as «class utf8»

    write this_data to the open_target_file starting at eof as «class utf8»
    

    Of course you have to append as «class utf8» as well when you read the file and the file is UTF8 encoded.

    And you can delete these two redundant lines

    set the target_file to the target_file as string
    set appleScriptfilePath to target_file as string