Skip to content

Commit cd5bcb2

Browse files
committed
Add basic parsing JSON example
1 parent da9ef26 commit cd5bcb2

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//// # Parsing JSON
2+
////
3+
//// The gleam_json library can be used to decode JSON.
4+
////
5+
//// ## Dependencies
6+
////
7+
//// - https://hex.pm/packages/gleam_json
8+
9+
import gleam/dict
10+
import gleam/dynamic
11+
import gleam/json
12+
import gleeunit/should
13+
14+
type User(name, age, is_admin) {
15+
User(name, age, is_admin)
16+
}
17+
18+
pub fn main_test() {
19+
// Basic string key-value pair
20+
"{\"name\": \"cookbook\"}"
21+
|> json.decode(dynamic.dict(dynamic.string, dynamic.string))
22+
|> should.equal(Ok(dict.from_list([#("name", "cookbook")])))
23+
24+
// String key-value pair with list of integers
25+
"{\"scores\": [1, 2, 3]}"
26+
|> json.decode(dynamic.dict(dynamic.string, dynamic.list(of: dynamic.int)))
27+
|> should.equal(Ok(dict.from_list([#("scores", [1, 2, 3])])))
28+
29+
// Custom decoder
30+
let decoder =
31+
dynamic.decode3(
32+
User,
33+
dynamic.field("name", dynamic.string),
34+
dynamic.field("age", dynamic.int),
35+
dynamic.field("is_admin", dynamic.bool),
36+
)
37+
"{\"name\": \"Alice\", \"age\": 42, \"is_admin\": true}"
38+
|> json.decode(decoder)
39+
|> should.equal(Ok(User("Alice", 42, True)))
40+
}

0 commit comments

Comments
 (0)