From: Matt S Trout Date: Tue, 19 Jun 2012 17:21:34 +0000 (+0000) Subject: beginnings of parser X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=scpubgit%2FTenDotTcl.git;a=commitdiff_plain;h=f5961f8c52877b8bc38bd289cb420b065cc81c64 beginnings of parser --- diff --git a/json.tcl b/json.tcl index 746a8df..67c1b2e 100644 --- a/json.tcl +++ b/json.tcl @@ -64,7 +64,7 @@ namespace eval ten::json { ^num|str|obj|list$ {} default { error [ concat "Invalid JSON type " [lindex $data 0 0] ] } } - return [ eval $data ] + eval $data } } @@ -95,19 +95,98 @@ namespace eval ten::json { ^num|str|obj|list$ {} default { error [ concat "Invalid JSON type " [lindex $data 0 0] ] } } - return [ eval $data ] + eval $data } } proc tclify_json {data} { tclify::tclify $data } + + namespace eval parse { + + variable json + + proc eat_comma {} { + variable json + set json [string trimleft $json] + if {[string index $json 0] eq ","} { + set json [string range $json 1 end] + } + } + + proc parse_list {} { + variable json + set json [ string range $json 1 end ] + set tcl {list} + while {"$json" ne ""} { + if {[string index $json 0] eq "]"} { + return $tcl + } + lappend tcl [ parse ] + eat_comma + } + error "Ran out of JSON. Confused now." + } + + proc parse_str {} { + variable json +puts $json + # like Text::Balanced except ugly (borrowed from tcvJSON's code) + set reStr {(?:(?:\")(?:[^\\\"]*(?:\\.[^\\\"]*)*)(?:\"))} + if {![regexp $reStr $json string]} { + error [ concat "Invalid string: " [string range $json 0 32] + } + set json [string range $json [string length $string] end] + # chop off outer ""s and substitute backslashes + # This does more than the RFC-specified backslash sequences, + # but it does cover them all + list str [subst -nocommand -novariable [string range $string 1 end-1]] + } + + proc parse {} { + variable json + set json [string trimleft $json] + if {$json eq ""} { + return + } + switch -regexp [string index $json 0] { + {\{} { parse_obj } + {\[} { parse_list } + {\"} { parse_str } + + {[-0-9]} { parse_number } + + default { error "argh" } + } + } + } + + proc parse_json {json} { + set parse::json $json + parse::parse + } } set ex_json { list {str foo} {num 0} {obj __remote_object__ {str 512}} {null} } +set jtext { + [ + "foo", + 0, + { + "__remote_object__": "512", + }, + null, + ] +} + puts [ ten::json::deparse_json $ex_json 2 ] dict for {k v} [ ten::json::tclify_json [ lindex [ ten::json::tclify_json $ex_json ] 2 ] ] { puts "$k: $v" } + +#puts [ ten::json::parse_json $jtext ] + +puts [ ten::json::parse_json {["foo"]} ]