Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse JSON in Racket?

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.

like image 632
Electric Coffee Avatar asked May 19 '14 18:05

Electric Coffee


1 Answers

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))
like image 95
Chris Jester-Young Avatar answered Nov 04 '22 02:11

Chris Jester-Young