Multilevel list to string

This shouldn’t be so hard. I want to return a multilevel list as a string. The following returns “{1,23}” instead of “{1,{2,3}}”. Can anyone straighten me out here? Thanks very much.

-Dan

global s
set s to ""
display dialog list2text({1,{2,3}})

on list2text(lst)
    set s to s & "{"
    repeat with itm in lst
        if class of itm is "list" then
            set s to s & list2text(itm) & ","
        else
            set s to s & itm & ","
        end if
    end repeat
    if (count of lst) > 1 then set s to text 1 through -2 of s -- remove final comma
    set s to s & "}"
    return s
end list2text

You can use this handler:
http://macscripter.net/exchange/comments.php?id=P312_0_1_0_C

Excellent, jj, thanks very much - that works fine. I’m still curious what was wrong with the code I posted, but I guess that’s no longer urgent, I now have what I need…I’d like to learn why…

Much obliged…

  • Dan

The above link is dead. Is there an alternate?

J

This is the code:

--> VARIOUS SAMPLES OF USAGE:

(*
set rec to "string" --> string
set rec to 4.6 --> number
set rec to current date --> date
set rec to {1, "a", {x:2}} --> list
set rec to {a:2, b:{1, 2, 3}, c:"d"} --> record
tell application "TextEdit" to set rec to first window --> TextEdit's object
tell application "Finder" to set rec to first item of desktop --> Finder's object
set rec to «data utxt0065» --> unicode text
set rec to whateverToString --> handler
script ha
	property foo : "bar"
end script
set rec to ha --> script object
set rec to real --> class
set rec to «class unkn» --> raw class

--> and the undefined value, which is the only I know can't be handled by this handler ;-)
set rec to (run script "«class undf»")

whateverToText(rec)
*)

--> and, here, the handler:
on whateverToText(x)
	try
		if class of x is in {string, Unicode text} then
			try
				count x
				return x
			on error msg --> handle data string/utxt
				return text 1 thru -39 of msg
			end try
		else
			tell application x to beep
		end if
	on error msg
		set msg to text 23 thru -2 of msg
		if msg starts with "(" and msg ends with ")" then --> unknown object
			return text 2 thru -2 of msg
		else
			return msg
		end if
	end try
end whateverToText

property |version| : 1.0
property author : "Pescados Software · pescadosweb.com"
property license : "freeware, open-source"

Thanks.

J