number parsing and nested array
[scpubgit/TenDotTcl.git] / json.tcl
index f9c9e68..4b8c13a 100644 (file)
--- a/json.tcl
+++ b/json.tcl
@@ -106,24 +106,51 @@ namespace eval ten::json {
 
     variable json
 
-    proc eat_comma {} {
+    proc eat_spaces {} {
       variable json
       set json [string trimleft $json]
-      if {[string index $json 0] eq ","} {
-        set json [string range $json 1 end]
+    }
+
+    proc eat_char {char} {
+      variable json
+      eat_spaces
+      if {[string index $json 0] eq "$char"} {
+        eat_any
       }
     }
 
-    proc parse_list {} {
+    proc eat_any {} {
       variable json
       set json [ string range $json 1 end ]
+    }
+
+    proc parse_list {} {
+      variable json
+      eat_any
       set tcl {list}
       while {"$json" ne ""} {
         if {[string index $json 0] eq "]"} {
+          eat_any
+          return $tcl
+        }
+        lappend tcl [ parse ]
+        eat_char ,
+      }
+      error "Ran out of JSON. Confused now."
+    }
+
+    proc parse_obj {} {
+      variable json
+      eat_char
+      set tcl {obj}
+      while {"$json" ne ""} {
+        if {[string index $json 0] eq "]"} {
+          eat_char
           return $tcl
         }
+        lappend tcl [ 
         lappend tcl [ parse ]
-        eat_comma
+        eat_char ,
       }
       error "Ran out of JSON. Confused now."
     }
@@ -142,9 +169,20 @@ namespace eval ten::json {
       list str [subst -nocommand -novariable [string range $string 1 end-1]]
     }
 
+    proc parse_num {} {
+      variable json
+      string is double -failindex last $json
+      if {$last == 0} {
+        error "Saw number but wasn't - $json"
+      }
+      set num [string range $json 0 [expr {$last - 1}]]
+      set json [string range $json $last end]
+      list num $num
+    }
+
     proc parse {} {
       variable json
-      set json [string trimleft $json]
+      eat_spaces
       if {$json eq ""} {
         return
       }
@@ -153,7 +191,7 @@ namespace eval ten::json {
         {\[} { parse_list }
         {\"} { parse_str }
 
-        {[-0-9]} { parse_number }
+        {[-0-9]} { parse_num }
 
         default { error "argh" }
       }
@@ -161,8 +199,13 @@ namespace eval ten::json {
   }
 
   proc parse_json {json} {
-    set parse::json $json
-    parse::parse
+    set parse::json [ string trim $json ]
+    set result [ parse::parse ]
+    parse::eat_spaces
+    if {$parse::json ne ""} {
+      error "Had JSON left over: $parse::json"
+    }
+    return $result
   }
 }
 
@@ -187,4 +230,4 @@ dict for {k v} [ ten::json::tclify_json [
 
 #puts [ ten::json::parse_json $jtext ]
 
-puts [ ten::json::parse_json {["foo"]} ]
+puts [ ten::json::parse_json {["foo",2345,["bar"]]} ]