Getting a property from a selected AppleScript Record

Hey guys,

I’m having some trouble in trying to figure out how could I fetch the |path| key, in an AppleScript record with nested records bellow, only to the record that has the |open| key set to true.

set theRecords to {|556cb0f3ff0edef5|:{|path|:"/a/path", |0f529f80e5f7feff|:{|path|:"/b/path", |open|:true, ts:1.606420606631E+12}}

Any ideas?

I thought this would be a fun exercise in recursion, but I came across this comment on records from Matt Neuburg’s AppleScript: The Definitive Guide:

There is no built-in way to obtain a list of the names of the items of a record. A record has no such introspective abilities. You (a human being) can see the names of the items of a record in AppleScript’s display of the record’s value. But your code can’t see this information; the names of the items are not values of any kind, and cannot easily be turned into values. I have seen many elaborate attempts to work around this problem, but I’m not going to show you any of them. This is a big shortcoming of AppleScript itself, and it needs to be fixed on the level of AppleScript itself.

A bit of Googling suggests this has not been fixed on the level of AppleScript itself. I don’t mean to be pessimistic, but there may be no way to do what you want to do. It might be better to switch from AppleScript to JavaScript (JXA), where you can use JSON for data structures like this.

1 Like

There is no built-in way to obtain a list of the names of the items of a record

(That was more or less true at the time)

use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

-- keys :: Dict -> [String]
on keys(rec)
    (current application's NSDictionary's dictionaryWithDictionary:rec)'s allKeys() as list
end keys

-- lookupDict :: String -> Dict -> any
on lookupDict(k, rec)
    -- Just the value of k in the dictionary,
    -- or missing value if k is not found.
    set ca to current application
    set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s objectForKey:k
    if missing value ≠ v then
        item 1 of ((ca's NSArray's arrayWithObject:v) as list)
    else
        missing value
    end if
end lookupDict

but as you say, JavaScript is a much less clumsy instrument.

(and AppleScript is in late sunset mode, not least because there is no scope for it on iOS)

Looks like I need to expand my toolkit beyond AppleScript. I see that JavaScript forks into JXA (is JXA a flavor of JavaScript?).

Do you recommend any resource for a beginner to get on those?

Recommendations I’ve previously got for AppleScript where really appreciated! Specially the Script Deubgger app and Sal’s book.

To anyone else who’s looking for the same thing as I am, take a look at this JMichealTX curated list: