pub fn encode_default<V: IntoJsonValue>(value: V) -> ToonResult<String>Expand description
Encode a JSON value to TOON format with default options.
This function accepts either JsonValue or serde_json::Value and converts
automatically.
ยงExamples
use toon_format::encode_default;
use serde_json::json;
// Simple object
let data = json!({"name": "Alice", "age": 30});
let toon = encode_default(&data)?;
assert!(toon.contains("name: Alice"));
assert!(toon.contains("age: 30"));
// Primitive array
let data = json!({"tags": ["reading", "gaming", "coding"]});
let toon = encode_default(&data)?;
assert_eq!(toon, "tags[3]: reading,gaming,coding");
// Tabular array
let data = json!({
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
});
let toon = encode_default(&data)?;
assert!(toon.contains("users[2]{id,name}:"));Examples found in repository?
More examples
examples/parts/round_trip.rs (line 15)
7pub fn round_trip() {
8 let original = json!({
9 "product": "Widget",
10 "price": 29.99,
11 "stock": 100,
12 "categories": ["tools", "hardware"]
13 });
14
15 let encoded = encode_default(&original).unwrap();
16 let decoded = decode_default(&encoded).unwrap();
17
18 println!("Encoded:\n{encoded}",);
19 println!("\nRound-trip equal: {}", original == decoded);
20}examples/parts/mixed_arrays.rs (line 9)
4pub fn mixed_arrays() {
5 // Mixed / non-uniform arrays (list format)
6 let mixed = json!({
7 "items": [1, {"a": 1}, "text"]
8 });
9 println!("{}", encode_default(&mixed).unwrap());
10
11 // Objects in list format: first field on hyphen line
12 let list_objects = json!({
13 "items": [
14 {"id": 1, "name": "First"},
15 {"id": 2, "name": "Second", "extra": true}
16 ]
17 });
18 println!("\n{}", encode_default(&list_objects).unwrap());
19}examples/parts/empty_and_root.rs (line 7)
4pub fn empty_and_root() {
5 // Empty containers
6 let empty_items = json!({ "items": [] });
7 println!("{}", encode_default(&empty_items).unwrap());
8
9 // Root array
10 let root_array = json!(["x", "y"]);
11 println!("\n{}", encode_default(&root_array).unwrap());
12
13 // Empty object at root encodes to empty output; print a marker
14 let empty_obj = json!({});
15 let out = encode_default(&empty_obj).unwrap();
16 if out.is_empty() {
17 println!("\n(empty output)");
18 } else {
19 println!("\n{out}");
20 }
21}examples/parts/tabular.rs (line 12)
4pub fn tabular() {
5 // Arrays of objects (tabular)
6 let items = json!({
7 "items": [
8 { "sku": "A1", "qty": 2, "price": 9.99 },
9 { "sku": "B2", "qty": 1, "price": 14.5 }
10 ]
11 });
12 let out = encode_default(&items).unwrap();
13 println!("{out}");
14
15 // Recursive tabular inside nested structures
16 let nested = json!({
17 "items": [
18 {
19 "users": [
20 { "id": 1, "name": "Ada" },
21 { "id": 2, "name": "Bob" }
22 ],
23 "status": "active"
24 }
25 ]
26 });
27 let out_nested = encode_default(&nested).unwrap();
28 println!("\n{out_nested}");
29}Additional examples can be found in: