#traversal

serde-ast

An AST representation for serde serialization

1 unstable release

0.1.0-alpha.1 Sep 18, 2024

#574 in Encoding

Download history 59/week @ 2024-09-12 107/week @ 2024-09-19 15/week @ 2024-09-26 10/week @ 2024-10-03

191 downloads per month

MIT/Apache

30KB
759 lines

serde-ast

Define an AST representation of serde serialization.

use serde::{Deserialize, Serialize};
use serde_ast::to_ast;

#[derive(Serialize, Deserialize)]
struct Example {
    hello: String,
}

let example = Example { hello: "World".to_string() };
let ast = to_ast(&example).expect("serialize to_ast");
println!("{}", ast);
Struct {
    name: "Example",
    len: 1,
    ops: [
        Field {
            key: "hello",
            value: Str(
                "World",
            ),
        },
    ],
}

Serializing the [Ast] is equivalent to directly serializing the original value.

// serialize the ast
let output = serde_json::to_string(&ast).expect("serde_json::to_string");
// serialize the value directly
let direct = serde_json::to_string(&example).expect("serde_json::to_string");
// the result is the same
assert_eq!(output, direct);

lib.rs:

Implements an [Ast] representation of [serde] serialization.

This allows to see the serialization calls made, inspect them, traverse, edit, or serialize with a serde::Serializer.

#[derive(Serialize, Deserialize)]
struct Example {
    hello: String,
}
let example = Example { hello: "World".to_string() };
let ast = to_ast(&example).expect("serialize to_ast");
println!("{}", ast);
Struct {
    name: "Example",
    len: 1,
    ops: [
        Field {
            key: "hello",
            value: Str(
                "World",
            ),
        },
    ],
}

Serializing the [Ast] is equivalent to directly serializing the original value.

// serialize the ast
let output = serde_json::to_string(&ast).expect("serde_json::to_string");
// serialize the value directly
let direct = serde_json::to_string(&example).expect("serde_json::to_string");
// the result is the same
assert_eq!(output, direct);

Dependencies

~0.4–1MB
~22K SLoC