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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With