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.
Asked
Active
Viewed 3,381 times
1 Answers
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
-
can you add an example for going back again? – Electric Coffee May 19 '14 at 18:57
-
Sure, just use `(jsexpr->string x)` for the example above. – C. K. Young May 19 '14 at 18:58
-
no I mean making data from scratch, and then turning it into a json string, I'm fairly new to racket, so bare with me – Electric Coffee May 19 '14 at 19:00
-
What kind of data do you want to create JSON of? I want to create a useful example. – C. K. Young May 19 '14 at 19:02
-
could you do a simple person data thing? you know with a first name, last name, age, and country or something, that'd be great – Electric Coffee May 19 '14 at 19:03
-
3Okay, here we go, added how to create JSON from a structure type. Enjoy! – C. K. Young May 19 '14 at 19:41
-
1Nice answer! It would be great if you submitted a pull request that adds examples like these to the docs. :) – Asumu Takikawa May 19 '14 at 21:28
-
@AsumuTakikawa Thanks! I don't currently see any examples in the `json` module documentation, where would these go? – C. K. Young May 19 '14 at 21:31