Updating read-json to produce eof when appropriate.

This commit is contained in:
Carl Eastlund 2012-10-02 12:01:28 -04:00
parent 937c901ce7
commit bc681836bc
3 changed files with 13 additions and 4 deletions

View File

@ -79,9 +79,10 @@ the @rfc for more information about JSON.
@defproc[(read-json [in input-port? (current-input-port)]
[#:null jsnull any? (json-null)])
jsexpr?]{
(or/c jsexpr? eof-object?)]{
Reads a @tech{jsexpr} from a JSON-encoded input port @racket[in] as a
Racket (immutable) value.}
Racket (immutable) value, or produces @racket[eof] if only whitespace
remains.}
@defproc[(string->jsexpr [str string?] [#:null jsnull any? (json-null)])
jsexpr?]{

View File

@ -156,7 +156,7 @@
(list (string->symbol k) (read-json)))
(apply hasheq (apply append (read-list 'object #rx#"^}" read-pair))))
;;
(define (read-json)
(define (read-json #:eof-ok? [eof-ok? #false])
(skip-whitespace)
(cond
[(regexp-try-match #px#"^true\\b" i) #t]
@ -171,9 +171,10 @@
(cond [(equal? m #"\"") (read-string)]
[(equal? m #"[") (read-list 'array #rx#"^\\]" read-json)]
[(equal? m #"{") (read-hash)])))]
[(and eof-ok? (regexp-try-match #px#"$" i)) eof]
[else (err "bad input")]))
;;
(read-json))
(read-json #:eof-ok? #true))
;; ----------------------------------------------------------------------------
;; Convenience functions

View File

@ -95,6 +95,13 @@
(string->jsexpr @T{ " \b\n\r\f\t\\\"\/ " }) => " \b\n\r\f\t\\\"/ "
(string->jsexpr @T{ "\uD834\uDD1E" }) => "\U1D11E"
(string->jsexpr @T{ "\ud834\udd1e" }) => "\U1d11e"
;; EOF detection
(for/list ([je (in-port read-json
(open-input-string
@T{ 1 [2,3] "four" }))])
je)
=>
'(1 (2 3) "four")
))
(test do (pred-tests)