|
| 1 | +// Encoding JSON data structures using Json.Encode |
| 2 | + |
| 3 | +// Encode string array, fast because `stringArray` only changes the type |
| 4 | +// prints ["foo", "bar"] |
| 5 | +let _ = ["foo", "bar"]->Json.Encode.stringArray->Js.log |
| 6 | + |
| 7 | +// Encode string array, slower but more flexible |
| 8 | +// prints ["foo", "bar"] |
| 9 | +let _ = ["foo", "bar"]->Json.Encode.array(Json.Encode.string, _)->Js.log |
| 10 | + |
| 11 | +// Encode object, fast but unsafe because it cannot guarantee that it only contains valid JSON |
| 12 | +// prints { x: 42, foo: 'bar' } |
| 13 | +let _ = Json.Encode.Unsafe.object({ |
| 14 | + "x": Json.Encode.int(42), |
| 15 | + "foo": Json.Encode.string("bar"), |
| 16 | +})->Js.log |
| 17 | + |
| 18 | +// Encode object, slower but safe |
| 19 | +// prints { x: 42, foo: 'bar' } |
| 20 | +let _ = Json.Encode.object([("x", Json.Encode.int(42)), ("foo", Json.Encode.string("bar"))])->Js.log |
| 21 | + |
| 22 | +//Advanced example: encode a record |
| 23 | + |
| 24 | +type point = { |
| 25 | + x: float, |
| 26 | + y: float, |
| 27 | +} |
| 28 | + |
| 29 | +type line = { |
| 30 | + points: array<point>, |
| 31 | + thickness: option<int>, |
| 32 | +} |
| 33 | + |
| 34 | +module Encode = { |
| 35 | + open! Json.Encode |
| 36 | + |
| 37 | + let point = r => |
| 38 | + Unsafe.object({ |
| 39 | + "x": float(r.x), |
| 40 | + "y": float(r.y), |
| 41 | + }) |
| 42 | + |
| 43 | + let line = (~points, ~thickness=?, ()) => |
| 44 | + Unsafe.object({ |
| 45 | + "points": array(point, points), |
| 46 | + "thickness": option(int, thickness), |
| 47 | + }) |
| 48 | +} |
| 49 | + |
| 50 | +let _ = Encode.line(~points=[{x: 1.1, y: -0.4}, {x: 5.3, y: 3.8}], ~thickness=2, ())->Js.log |
0 commit comments