Skip to content

Commit 9ab6329

Browse files
committed
docs: add examples
1 parent 010f23c commit 9ab6329

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

examples/DecodeExample.res

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
type point = {
2+
x: int,
3+
y: int,
4+
}
5+
6+
type polyline = {
7+
points: array<point>,
8+
thickness: option<int>,
9+
}
10+
11+
module Decode = {
12+
open Json.Decode
13+
14+
let point = object(field => {
15+
x: field.required(. "x", int),
16+
y: field.required(. "y", int),
17+
})
18+
19+
let polyline = object(field => {
20+
points: field.required(. "points", array(point)),
21+
thickness: field.optional(. "thickness", int),
22+
})
23+
}
24+
25+
let data = `{
26+
"points": [
27+
{ "x": 1, "y": -4 },
28+
{ "x": 5, "y": 8 }
29+
]
30+
}`
31+
32+
let _ = data->Js.Json.parseExn->Json.decode(Decode.polyline)->Js.log

examples/EncodeExample.res

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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

Comments
 (0)