Converting Struct to JSON

Hello, and thanks for answering my beginner question!

If I have this struct in typed racket:

#lang typed/racket
(struct Person ([name : String] [age : Number] [gender : Boolean]))

What's the easiest method of converting it to a JSON string?

(Expected Input/Output: (Person "John Smith" 28 #f)/{ "name": "John Smith", "age": 28, gender: false }

2 Likes

You have to write a function to convert your struct into a JSON representation - objects map well. The tjson package provides Typed Racket support for JSON:

#lang typed/racket

(require tjson)

(struct Person ([name : String] [age : Number] [gender : Boolean]))

(: person->json : Person -> JsObject)
(define (person->json p)
  (jsobject `((name . ,(Person-name p)) (age . ,(Person-age p)) (gender . ,(Person-gender p)))))
;; or
;; (define (person->json p)
;;  (hasheq 'name (Person-name p) 'age (Person-age p) 'gender (Person-gender p)))

(displayln (json->string (person->json (Person "John Smith" 28 #f))))

Most (All?) Racket JSON libraries expect objects to be hash tables with symbol keys. the tjson jsobject function converts an alist to one, with constraints on the argument type so it only gets Racket values that map to json types. Creating the hash table directly is more efficient but might result in less useful errors when using invalid types.

2 Likes

Thank you so much for the answer! It works!