namespace eval ton::nr { namespace export json2ton variable version 0.1 } proc ton::nr::json2ton json { set ton "" set l [string length $json] set d {, \} \]} set cl "" set key false set i 0 while {$i<$l} { # skip leading whitespace while {[set c [string index $json $i]] eq "\n" || [string is space $c] && $i<$l } {incr i} switch -exact [string index $json $i] { \" { for {set j [incr i]} {$i<$l} {incr i} { set i [string first \" $json $i] if {[string index $json $i-1] ne "\\"} break } if {!$key} {append ton "s "} append ton [list [string range $json $j $i-1]] incr i } t {append ton "l true"; incr i 4} f {append ton "l false"; incr i 5} n {append ton "l null"; incr i 4} 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - - { set float false for {set j $i} {$i<$l} {incr i} { if {[set c [string index $json $i]] in $d} break set float [expr {$float || [string match "\[eE.]" $c]}] } set num [string trimright [string range $json $j $i-1]] if {$float} { if {[string is double $num]} { append ton "d $num" } else { error "number: invalid double $num." } } elseif {[string is integer $num]} { append ton "i $num" } else { error "number: invalid integer $num." } } \[ { append ton "a \[" set d {, \]} set cl "\]$cl" incr i } \{ { append ton "o " set d {: , \}} set cl "\}$cl" set key true incr i } : { append ton " \[" if {!$key} {error "unexpected ':'"} set key false incr i } , { append ton "\]" if {[string index $cl 0] eq "\}"} { append ton " " set key true } else { append ton " \[" } incr i } \] { append ton \] set d {, \] \}} set cl [string range $cl 1 end] incr i } \} { append ton \] set d {, \] \}} set cl [string range $cl 1 end] incr i } "" {break} default {error "unexpected '[string index $json $i]'"} } } return $ton }