• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Converting Associative List to Record
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Converting Associative List to Record


  • Subject: Re: Converting Associative List to Record
  • From: kai <email@hidden>
  • Date: Thu, 06 Nov 2003 20:12:57 +0000

on Thu, 6 Nov 2003 13:28:07 +0100, Frank <email@hidden> wrote:

> As a new Applescript user I was wondering if there is an easy way to
> create records from associative list:
>
> For example to convert the list
>
> {"name", "Frank", "city", "Brussels"}
>
> to
>
> {name: "frank", city: "Brussels"}

Welcome to the wonderful world of AppleScript, Frank.

Try something along these lines:

--------------------

on recordFromList(l)
set c to count l
if c mod 2 > 0 then error "Can't convert odd number of items to record."
set r to {}
repeat with n from 1 to c by 2
set {k, v} to l's items n thru (n + 1)
set r to r & (run script "{" & k & ":\"" & v & "\"}")
end repeat
r
end recordFromList

set l to {"name", "Frank", "city", "Brussels"}

recordFromList(l)

--> {name:"Frank", city:"Brussels"}

--------------------

If you need to include values other than strings in your list, things become
just a little more complicated. Something like this might help (watch out
for line wraps):

--------------------

on textFrom(v)
try
e of v
on error e
e's text 16 thru -2
end try
end textFrom

on recordFromList(l)
set c to count l
if c mod 2 > 0 then error "Can't convert odd number of items to record."
set r to {}
repeat with n from 1 to c by 2
set {k, v} to l's items n thru (n + 1)
set r to r & (run script "{" & k & ":" & textFrom(v) & "}")
end repeat
r
end recordFromList

set l to {"text", "hello", "integer", 3, "real", 12.8, "list", {"a", "b",
3}, "record", {a:1, b:2}}

recordFromList(l)

--> {text:"hello", integer:3, real:12.8, list:{"a", "b", 3}, record:{a:1,
b:2}}

--------------------

---
kai
_______________________________________________
applescript-users mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/applescript-users
Do not post admin requests to the list. They will be ignored.

  • Prev by Date: Re: Volume index bug in Panther?
  • Next by Date: illustrator-scripting, again ...
  • Previous by thread: Re: Converting Associative List to Record
  • Next by thread: Re: Converting Associative List to Record
  • Index(es):
    • Date
    • Thread