->jsexpr:   Generics for converting data to JSON
1 Reference
gen:  to-jsexpr
to-jsexpr?
->jsexpr
add-to-jsexpr-fallback!
define-struct->jsexpr
camel  Case-convention
kebab-case-convention
snake_  case-convention
9.0

->jsexpr: Generics for converting data to JSON🔗ℹ

Bogdan Popa <bogdan@defn.io>

This library provides a generic interface (with defaults) for converting common Racket data to JSON.

1 Reference🔗ℹ

 (require json/to-jsexpr) package: to-jsexpr-lib

interface

gen:to-jsexpr : any/c

procedure

(to-jsexpr? v)  boolean?

  v : any/c
The generic interface and predicate for values that can be converted to jsexpr?s.

A struct implementing gen:to-jsexpr must provide an implementation for ->jsexpr.

procedure

(->jsexpr v)  jsexpr?

  v : to-jsexpr?
Converts v to a jsexpr?. The values passed to this procedure may be any instance of a struct that implements gen:to-jsexpr, or any value satisfying the following predicates:

If v is a hash, its keys must all be symbols. Otherwise, a contract error is raised. For any container types listed above, the ->jsexpr is applied recursively to v’s children.

When you can’t make a value conform to gen:to-jsexpr, use add-to-jsexpr-fallback! to register a fallback handler for those types of values.

procedure

(add-to-jsexpr-fallback! predicate convert)  void?

  predicate : (-> any/c boolean?)
  convert : (-> any/c jsexpr?)
Registers a fallback handler for ->jsexpr that matches values for whom predicate produces #t and converts them to jsexpr?s using convert.

syntax

(define-struct->jsexpr struct-id maybe-convention)

 
maybe-convention = 
  | #:convention convention-id
Defines a ->jsexpr implementation for struct-id that automatically exposes all of its fields and translates them to keys using the given convention-id. When no convention is provided, camelCase-convention is used.

Examples:
> (require json/to-jsexpr)
> (struct example1 (field-a field-b)
    #:methods gen:to-jsexpr
    [(define-struct->jsexpr example1)])
> (->jsexpr (example1 'a 42))

'#hasheq((fieldA . "a") (fieldB . 42))

> (struct example2 (field-a field-b)
    #:methods gen:to-jsexpr
    [(define-struct->jsexpr example2
       #:convention snake_case-convention)])
> (->jsexpr (example2 'a 42))

'#hasheq((field_a . "a") (field_b . 42))

The available conventions for converting the hyphens in struct field identifiers to hash? keys.