]> gitweb.factorcode.org Git - factor.git/commitdiff
json.reader: make path>jsons check for balanced brackets.
authorJohn Benediktsson <mrjbq7@gmail.com>
Thu, 11 Mar 2021 02:19:48 +0000 (18:19 -0800)
committerJohn Benediktsson <mrjbq7@gmail.com>
Thu, 11 Mar 2021 02:19:48 +0000 (18:19 -0800)
basis/json/reader/reader-docs.factor
basis/json/reader/reader.factor

index 204f630ed74a8e7aaa222d0809e28f8227552afa..dd4140ce79055770a9c41ec5a0a88ec4100636a8 100644 (file)
@@ -22,7 +22,7 @@ HELP: path>json
 HELP: path>jsons
 { $values
     { "path" "a pathname string" }
-    { "jsons" "a sequences of JSON objects" }
+    { "jsons" { $sequence "JSON objects" } }
 }
 { $description "Reads a file into a sequence of JSON objects and returns them all." } ;
 
index 95e39f1e63ea32abf860edbef88de20e14b6d80f..afb5188a92a6cd78a9a6ec148488d6fcfd2328c6 100644 (file)
@@ -10,7 +10,7 @@ IN: json.reader
 
 ERROR: not-a-json-number string ;
 
-SYMBOL: counter
+SYMBOL: json-depth
 
 : json-number ( char stream -- num char )
     [ 1string ] [ "\s\t\r\n,:}]" swap stream-read-until ] bi*
@@ -111,9 +111,9 @@ DEFER: (read-json-string)
     { object vector object } declare
     {
         { CHAR: \" [ over read-json-string suffix! ] }
-        { CHAR: [  [ 1 counter +@ json-open-array ] }
+        { CHAR: [  [ 1 json-depth +@ json-open-array ] }
         { CHAR: ,  [ v-over-push ] }
-        { CHAR: ]  [ -1 counter +@ json-close-array ] }
+        { CHAR: ]  [ -1 json-depth +@ json-close-array ] }
         { CHAR: {  [ json-open-hash ] }
         { CHAR: :  [ v-pick-push ] }
         { CHAR: }  [ json-close-hash ] }
@@ -128,12 +128,13 @@ DEFER: (read-json-string)
     } case ;
 
 : json-read-input ( stream -- objects )
-    V{ } clone over '[ _ stream-read1 ] [ scan ] while* nip ;
+    0 json-depth [
+        V{ } clone over '[ _ stream-read1 ] [ scan ] while* nip
+        json-depth get zero? [ json-error ] unless
+    ] with-variable ;
 
-
-! A properly formed JSON input should contain exactly one object with balanced brackets.
-: get-json ( objects  --  obj  )
-    dup length 1 = counter get 0 = and [ first ] [ json-error ] if ;
+: get-json ( objects  --  obj )
+    dup length 1 = [ first ] [ json-error ] if ;
 
 PRIVATE>
 
@@ -143,11 +144,10 @@ PRIVATE>
 GENERIC: json> ( string -- object )
 
 M: string json>
-    [ 0 counter [ read-json get-json ] with-variable ] with-string-reader ;
+    [ read-json get-json ] with-string-reader ;
 
 : path>json ( path -- json )
-    utf8 [ 0 counter [ read-json get-json ] with-variable ] with-file-reader ;
+    utf8 [ read-json get-json ] with-file-reader ;
 
-! Read a file with one json object per line
 : path>jsons ( path -- jsons )
     utf8 [ read-json ] with-file-reader ;