Use toon.Marshal to convert Go structs into TOON format and toon.Unmarshal to populate structs from TOON data. To map struct fields to TOON keys, use the toon struct tag.
toon.Marshal accepts an optional functional option toon.WithLengthMarkers(bool) to include length markers in the output.
package main
import (
"fmt"
"github.com/toon-format/toon-go"
)
type User struct {
ID int `toon:"id"`
Name string `toon:"name"`
Role string `toon:"role"`
}
type Payload struct {
Users []User `toon:"users"`
}
func main() {
in := Payload{
Users: []User{
{ID: 1, Name: "Alice", Role: "admin"},
{ID: 2, Name: "Bob", Role: "user"},
},
}
// Marshal with length markers enabled
encoded, err := toon.Marshal(in, toon.WithLengthMarkers(true))
if err != nil {
panic(err)
}
fmt.Println(string(encoded))
// Unmarshal into a struct
var out Payload
if err := toon.Unmarshal(encoded, &out); err != nil {
panic(err)
}
fmt.Printf("first user: %+v\n", out.Users[0])
}