| 1 | import json |
| 2 | |
| 3 | struct Json2 { |
| 4 | inner []f64 |
| 5 | } |
| 6 | |
| 7 | struct Json { |
| 8 | Json2 |
| 9 | test f64 |
| 10 | } |
| 11 | |
| 12 | struct Article { |
| 13 | title string |
| 14 | description string |
| 15 | } |
| 16 | |
| 17 | struct ArticlePlus { |
| 18 | Article |
| 19 | perex string |
| 20 | } |
| 21 | |
| 22 | fn test_main() { |
| 23 | str := '{"inner":[1,2,3,4,5],"test":1.2}' |
| 24 | data := json.decode(Json, str) or { |
| 25 | eprintln('Failed to decode json, error: ${err}') |
| 26 | return |
| 27 | } |
| 28 | println(data) |
| 29 | assert data.inner.len == 5 |
| 30 | assert data.inner[0] == 1.0 |
| 31 | assert data.inner[4] == 5.0 |
| 32 | assert data.test == 1.2 |
| 33 | |
| 34 | data_json := json.encode(data) |
| 35 | dump(data_json) |
| 36 | assert data_json == str |
| 37 | } |
| 38 | |
| 39 | fn test_encode_array_of_embedded_structs() { |
| 40 | list_of_object := [ |
| 41 | ArticlePlus{ |
| 42 | title: 'One good title' |
| 43 | description: 'this is the first' |
| 44 | }, |
| 45 | ArticlePlus{ |
| 46 | title: 'Other good title' |
| 47 | description: 'more one' |
| 48 | }, |
| 49 | ArticlePlus{ |
| 50 | title: 'Other good title' |
| 51 | description: 'more one' |
| 52 | perex: 'good perex' |
| 53 | }, |
| 54 | ] |
| 55 | assert json.encode(list_of_object) == '[{"title":"One good title","description":"this is the first","perex":""},{"title":"Other good title","description":"more one","perex":""},{"title":"Other good title","description":"more one","perex":"good perex"}]' |
| 56 | } |
| 57 | |