Convert string into a property

Hi all,

I have a list of records and I would like to get the value of one of the records items. The problem is that I only have the name of the property that I want to access as a string, so somehow I need to convert the string into a property like so:

set myRecords to {SKU1:"7", SKU2:"9", SKU3:"4"}

set propertyVar to "SKU1"

set myVar to propertyVar of myRecords

I found some code that would convert 2 strings into a record:

set string1 to "SKU1"
set string2 to "7"
set myRecord to (run script ("return {|" & string1 & "|:\"" & string2 as string) & "\"}")

return SKU1 of myRecord

I just figure out how to convert a string into a property without also setting its value.

Thanks,
Nik

Hi,

the easiest way nowadays is to use AppleScriptObjC

use framework "Foundation"

set myRecords to {SKU1:"7", SKU2:"9", SKU3:"4"}
set cocoaRecords to current application's NSDictionary's dictionaryWithDictionary:myRecords
set propertyVar to "SKU1"
set myVar to (cocoaRecords's objectForKey:propertyVar) as text

Hi Stefan,

that works perfectly. I must admit that I’ve never used AppleScriptObjC before, maybe I should start looking into this further.

Many Thanks,
Nik

The plain AppleScript solution would be dirty:

set myRecords to {SKU1:"7", SKU2:"9", SKU3:"4"}

set p to "SKU1"

set theScript to "on run argv
	return " & p & " of item 1 of argv
end"

run script theScript with parameters {myRecords}

Thanks DJ,

this works perfectly as well.

Am I right in thinking that if you pass a string to another script without quoting it the value is seen as a property?

Many Thanks,
Nik

That’s correct. We’re making use of eval which is compiling and executing generated code (executing arbitrary code). It’s considered harmful in professional programming but we’re talking AppleScript so it’s fine :wink:

What it basically does is generate the following code for compilation and execution:

on run argv
   return SKU1 of item 1 of argv
end"

Great,

Thanks again DJ.

Anyway the power of Cocoa is much more efficient than cumbersome and slow second level evaluation.

But what if you use that key multiple times? The power of record access in vanilla AppleScript is 100+ times faster and efficient than in ASObjC. So these kind of discussions are somewhat useless because there are many situations where the overhead of “slow second level evaluation” will become minor and the cumbersomeness of the bridge will become a problem.