forked from toon-format/toon-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtabular.rs
More file actions
96 lines (87 loc) · 2.18 KB
/
Copy pathtabular.rs
File metadata and controls
96 lines (87 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use serde::{Deserialize, Serialize};
use serde_json::json;
use toon_format::encode_default;
#[derive(Debug, Serialize, Deserialize)]
struct Item {
sku: String,
qty: i32,
price: f64,
}
#[derive(Debug, Serialize, Deserialize)]
struct Items {
items: Vec<Item>,
}
#[derive(Debug, Serialize, Deserialize)]
struct User {
id: i32,
name: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct Container {
users: Vec<User>,
status: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct NestedItems {
items: Vec<Container>,
}
pub fn tabular() {
// JSON example: Arrays of objects (tabular)
let items = json!({
"items": [
{ "sku": "A1", "qty": 2, "price": 9.99 },
{ "sku": "B2", "qty": 1, "price": 14.5 }
]
});
let out = encode_default(&items).unwrap();
println!("{out}");
// Struct with tabular array
let items = Items {
items: vec![
Item {
sku: "A1".to_string(),
qty: 2,
price: 9.99,
},
Item {
sku: "B2".to_string(),
qty: 1,
price: 14.5,
},
],
};
let out = encode_default(&items).unwrap();
println!("\n{out}");
// JSON example: Recursive tabular inside nested structures
let nested = json!({
"items": [
{
"users": [
{ "id": 1, "name": "Ada" },
{ "id": 2, "name": "Bob" }
],
"status": "active"
}
]
});
let out_nested = encode_default(&nested).unwrap();
println!("\n{out_nested}");
// Struct with nested tabular array
let nested_items = NestedItems {
items: vec![Container {
users: vec![
User {
id: 1,
name: "Ada".to_string(),
},
User {
id: 2,
name: "Bob".to_string(),
},
],
status: "active".to_string(),
}],
};
let out = encode_default(&nested_items).unwrap();
println!("\n{out}");
}