graphrustserdepetgraph

How do I serialize and deserialize a graph using Serde with Petgraph?


The Petgraph documentation hints at Serde support. Under "current features":

serde-1 - Defaults off. Enables serialization for Graph, StableGraph using serde 1.0. May require a more recent version of Rust than petgraph alone.

I can see the file serde_utils.rs in the source, but I've found no examples showing how to get Serde support working.

I'm aware of how to enable an optional crate feature. My question is aimed at getting serialization and deserialization to work.


Solution

  • Here is an example:

    use petgraph::graph::UnGraph;
    
    fn main() {
        // Create an undirected graph with `i32` nodes and edges with `()` associated data.
        let g = UnGraph::<i32, ()>::from_edges(&[(1, 2), (2, 3), (3, 4), (1, 4)]);
    
        // Serialize it to a JSON string.
        let j = serde_json::to_string(&g).unwrap();
    
        let i: UnGraph<i32, ()> = serde_json::from_str(&j).unwrap();
    
        assert!(petgraph::algo::is_isomorphic(&i, &g));
    }
    

    All you need is in the documentation.