Reading and writing plists from Execute Script actions

Here, in case it’s more illuminating, is an AppleScript translation

(AppleScript versions of writePlist() and readPlist() – note that in AS you will need to open with the line

use framework "Foundation"

which is not needed in JavaScript for Automation

(the generic map function, used in the example, is an illustrative imitation of something built into JS)

use framework "Foundation"

-- writePlist :: Object -> String -> IO ()
on writePlist(asObject, strPath)
    set a to current application
    set cClass to class of asObject
    
    if (cClass is record) then
        set objcObject to a's NSDictionary's dictionaryWithDictionary:asObject
    else if (cClass is list) then
        set objcObject to a's NSArray's arrayWithArray:asObject
    else
        return missing value
    end if
    
    (objcObject)'s ¬
        writeToFile:((a's NSString's stringWithString:strPath)'s ¬
            stringByStandardizingPath()) atomically:true
end writePlist

-- readPlist :: String -> Object
on readPlist(strPath)
    set a to current application
    set oPath to (a's NSString's stringWithString:strPath)'s ¬
        stringByStandardizingPath()
    
    set maybeDict to (a's NSDictionary's dictionaryWithContentsOfFile:oPath)
    if (maybeDict is not missing value) then return maybeDict as record
    
    set maybeArray to (a's NSArray's arrayWithContentsOfFile:oPath)
    if (maybeArray is not missing value) then return maybeArray as list
end readPlist

-- GENERIC MAP FUNCTION
-- (given a list, return a transformed copy, 
--  to each member of which some function f 
--  has been applied )

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    script mf
        property lambda : f
    end script
    
    set lng to length of xs
    set lst to {}
    repeat with i from 1 to lng
        set end of lst to mf's lambda(item i of xs, i, xs)
    end repeat
    return lst
end map


-- TWO EXAMPLES: plists with <dict> or <array> at the top level

set lstObjects to [¬
    {alpha:1, beta:2, gamma:3}, ¬
    [{delta:4, epsilon:5, zeta:6}, ¬
        {eta:"seven", theta:"eight", iota:"nine"}]]


on writeAndRead(obj, i)
    set strPath to item i of ["~/Desktop/test05.plist", "~/Desktop/test06.plist"]
    
    writePlist(obj, strPath)
    
    return readPlist(strPath)
end writeAndRead

map(writeAndRead, lstObjects)
2 Likes