I execute AppleScript in typescript which returns string(but it actually contains array). Is it possible to convert this string to array of items in typescript?
This is the code that returns string of array from AppleScript
import { Detail } from "@raycast/api";
import {runAppleScript} from 'run-applescript';
import { spawnSync } from "child_process";
async function spacesArray(): Promise<String> {
const out = spawnSync("defaults read com.pradeepb28.spacesfor myNewArray", { shell: true });
return String(out.output[1]).trim();
}
result(in string format):
(
abc,
abcd,
abcdef
)
CodePudding user response:
return String(out.output[1]).trim().split(",");
CodePudding user response:
The run-applescript
module calls out to the command-line osascript
, which, as you’ve discovered, is lousy for passing complex arguments and results.
If you wish to parse its output directly, you will need to add the -ss
flag to the osascript
command. That will format the output as AppleScript literals, which can be reliably parsed. The default output format is “human-readable”, which is ambiguous at best.
Another option would be for your AppleScript code to format the list of strings as a JSON string and return that, which you can trivially parse using JSON.parse()
. AppleScript doesn’t have built-in JSON support, but you can call Cocoa’s NSJSONSerialization
class via the AppleScript-ObjC bridge. It’s a bit more work, but it’s robust. This would be your safest route as it avoids introducing any additional dependencies and JSON data is well understood.
A third option would be to avoid osascript
and call NSAppleScript
from JS via the objc
bridge. The objc
bridge itself is a bit rough and unfinished (I have a PR on that but its author is busy with other work), but may be adequate for your needs. Unpacking the NSAppleEventDescriptor
s returned by -[NSAppleScript executeAndReturnError:]
is tedious, but reliable.
The last option is to ditch AppleScript entirely and use nodeautomation
to do your application scripting directly from JS. However, while nodeautomation
works well (I use it in my own work) I provide no warranty or free support.
Sorry there’s no really good solutions, but given how thoroughly Apple wrecked Mac Automation it’s a miracle it’s still alive at all.