如何在Racket中解析JSON?

时间:2014-05-19 18:31:14

标签: json parsing racket

我似乎无法找出{documentation},但实际上并没有任何解析一些简单JSON数据的例子,所以我想知道这里是否有人可以给我一些例子开始。

1 个答案:

答案 0 :(得分:17)

这是一个非常简单的例子:

(require json)
(define x (string->jsexpr "{\"foo\": \"bar\", \"bar\": \"baz\"}"))
(for (((key val) (in-hash x)))
  (printf "~a = ~a~%" key val))

以下是如何将它与基于JSON的API一起使用:

(require net/http-client json)
(define-values (status header response)
  (http-sendrecv "httpbin.org" "/ip" #:ssl? 'tls))
(define data (read-json response))
(printf "My IP address is ~a~%" (hash-ref data 'origin))

根据OP的要求,以下是如何从结构类型创建JSON值:

(require json)
(struct person (first-name last-name age country))
(define (person->jsexpr p)
  (hasheq 'first-name (person-first-name p)
          'last-name (person-last-name p)
          'age (person-age p)
          'country (person-country p)))
(define cky (person "Chris" "Jester-Young" 33 "New Zealand"))
(jsexpr->string (person->jsexpr cky))