package ppx_deriving_jsonschema

  1. Overview
  2. Docs
Jsonschema generator for ppx_deriving

Install

dune-project
 Dependency

Authors

Maintainers

Sources

ppx_deriving_jsonschema-0.0.8.tbz
sha256=c5a2f8c1d906c1890bcde81aa149cc38e479878eb6c1c45a8455d03a95a07c2e
sha512=c0e661717244bf62132a21ef975db2720597b1d8013b0221c1d7db5adfc14928caf675c0f2fd89869ee6f4f96527599e556a0c123cd9dc7f65cad8f81de322ef

doc/src/ppx_deriving_jsonschema.runtime/Ppx_deriving_jsonschema_runtime_classify.ml.html

Source file Ppx_deriving_jsonschema_runtime_classify.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
type t =
  [ `Null
  | `String of string
  | `Float of float
  | `Int of int
  | `Bool of bool
  | `List of t list
  | `Assoc of (string * t) list
  ]

let classify value =
  match%platform () with
  | Server -> value
  | Client ->
    (* [Js.Json.classify] only checks for [=== null] when distinguishing null from object, so it
     mis-classifies [undefined] as [JSONObject]. melange-json's [@option] [@drop_default] codegen
     emits [Js.Undefined.empty] for [None], so an [_to_json] result can legitimately contain
     [undefined] values that we have to handle here. We treat them as absent fields, matching
     [JSON.stringify] (which drops undefined object members and turns undefined array elements
     into null). *)
    let rec decode json =
      match Js.Json.classify json with
      | JSONNull -> `Null
      | JSONString s -> `String s
      | JSONNumber n ->
        let i = int_of_float n in
        if float_of_int i = n then `Int i else `Float n
      | JSONFalse -> `Bool false
      | JSONTrue -> `Bool true
      | JSONArray arr -> `List (Array.to_list (Array.map decode arr))
      | JSONObject dict ->
        let is_undefined json = Js.typeof json = "undefined" in
        `Assoc
          (Array.fold_right
             (fun (k, v) acc -> if is_undefined v then acc else (k, decode v) :: acc)
             (Js.Dict.entries dict) [])
    in
    decode value

let declassify value =
  match%platform () with
  | Server -> value
  | Client ->
    let rec encode = function
      | `Null -> Js.Json.null
      | `String str -> Js.Json.string str
      | `Float f -> Js.Json.number f
      | `Int i -> Js.Json.number (Js.Int.toFloat i)
      | `Bool b -> Js.Json.boolean b
      | `List li -> Js.Json.array (Array.of_list (List.map encode li))
      | `Assoc assoc -> Js.Json.object_ (Js.Dict.fromList (List.map (fun (k, v) -> k, encode v) assoc))
    in
    encode value