Version 0 of Tclon

Updated 2008-02-02 13:05:40 by sarnold

Sarnold: An attempt to produce a Tcl-equivalent to JSON, a data format easily parsable by Web applications. Here we have a simple code to handle this format at Tcl-level, with a little sugar to handle types, that will be needed by the Javascript version.

The Javascript code is yet to be done.


Tcl code:

proc tclon {data {type *}} {
	if {![llength $type] || $type eq "*"} {return $data}
	set res ""
	foreach t $type d $data {
		if {[llength $t]<=1} {
			switch $t {
				dict - list {
					lappend res [list $t $d]
				}
				default {
					lappend res $d
				}
			}
		} else {
			lappend res [linsert [tclon $d [lrange $t 1 end]] 0 [lindex $t 0]]
		}
	}
	#foreach d [lrange $data [llength $type] end] {lappend res $d}
	set res
}

proc fromtclon {data {type *}} {
	if {![llength $type] || $type eq "*"} {return $data}
	set res [list]
	foreach t $type d $data {
		if {[llength $t]<=1} {
			switch $t {
				dict - list {
					lappend res [lrange $d 1 end]
				}
				default {
					lappend res $d
				}
			}
		} else {
			lappend res [lrange [fromtclon $d [lrange $t 1 end]] 1 end]
		}
	}
	#foreach d [lrange $data [llength $type] end] {lappend res $d}
	set res
}

Some testing:

proc ? {s r} {
	if {![string equal $r [uplevel 1 $s]]} {error "assertion failed"}
}

proc validate {data type} {
	set out [fromtclon [tclon $data $type] $type]
	if {$out ne $data} {puts "Difference:"
	puts "1: $data"
	puts "2: [tclon $data $type]"
	puts "3: $out"
	error "assertion failed"
	}
}

? {tclon 1 int} 1
? {tclon {a b}} {a b}
? {tclon [list [list a b] b c] {{list *} *}} {{list a b} b c}
validate 1 int
validate {a b} {s s}
validate {{a b} b c} {{list *} *}