Skip to main content

JSON

JSON is supported out of the box. Primitives and types consisting only of primitves are automatically serializable and deserializable. Use auto(ToJson, FromJson) on your structs to make them serializable/deserializable as well.

src/strings.duck
[auto(ToJson, FromJson, ToString)]
struct Person {
name: String,
age: Int,
}

fn main() {
const array_as_json = [1, 2, 3, 4].to_json(); // use to_json to convert to to_json
const json_as_array = match parse_json<Int[]>(array_as_json) { // use parse_json to convert from json
Int[] @v => v,
else => std::error::panic("error occured during parsing"),
};
std::io::println(f"JSON: {array_as_json}, Parsed: {json_as_array.to_string()}");

const person_array_as_json = [Person { name: "John Smith", age: 44 }].to_json();
const json_as_person_array = match parse_json<Person[]>(person_array_as_json) {
Person[] @v => v,
else => std::error::panic("error occured during parsing"),
};
std::io::println(f"JSON: {person_array_as_json}, Parsed: {json_as_person_array.to_string()}");
}