11

I can't seem to figure out the {documentation}, there aren't really any examples of parsing some simple JSON data, so I was wondering if anyone here could give me some examples to get started.

Community
  • 1
  • 1
Electric Coffee
  • 11,733
  • 9
  • 70
  • 131

1 Answers1

24

Here's a very simple example:

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

Here's how you can use it with a JSON-based 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))

At the OP's request, here's how you can create a JSON value from a structure type:

(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))
C. K. Young
  • 219,335
  • 46
  • 382
  • 435