1 | import json |
2 | |
3 | struct User { |
4 | name string |
5 | age int |
6 | mut: |
7 | is_registered bool |
8 | } |
9 | |
10 | fn main() { |
11 | s := '[{ "name":"Frodo", "age":25}, {"name":"Bobby", "age":10}]' |
12 | mut users := json.decode([]User, s) or { |
13 | eprintln('Failed to parse json') |
14 | return |
15 | } |
16 | for user in users { |
17 | println('${user.name}: ${user.age}') |
18 | } |
19 | println('') |
20 | for i, user in users { |
21 | println('${i}) ${user.name}') |
22 | if !user.can_register() { |
23 | println('Cannot register ${user.name}, they are too young') |
24 | } else { |
25 | users[i].register() |
26 | println('${user.name} is registered') |
27 | } |
28 | } |
29 | // Let's encode users again just for fun |
30 | println('') |
31 | println(json.encode(users)) |
32 | } |
33 | |
34 | fn (u User) can_register() bool { |
35 | return u.age >= 16 |
36 | } |
37 | |
38 | fn (mut u User) register() { |
39 | u.is_registered = true |
40 | } |