Expand description
JSON format I/O for graphs
This module provides functionality for reading and writing graphs in JSON format. The JSON format provides a flexible, human-readable representation of graph structures with support for arbitrary node and edge attributes.
§Format Specification
The JSON graph format uses the following structure:
{
"directed": false,
"nodes": [
{"id": "node1", "data": {...}},
{"id": "node2", "data": {...}}
],
"edges": [
{"source": "node1", "target": "node2", "weight": 1.5},
{"source": "node2", "target": "node3", "weight": 2.0}
]
}§Examples
§Unweighted graph:
{
"directed": false,
"nodes": [
{"id": "1"},
{"id": "2"},
{"id": "3"}
],
"edges": [
{"source": "1", "target": "2"},
{"source": "2", "target": "3"}
]
}§Weighted graph:
{
"directed": true,
"nodes": [
{"id": "1", "label": "Start"},
{"id": "2", "label": "Middle"},
{"id": "3", "label": "End"}
],
"edges": [
{"source": "1", "target": "2", "weight": 1.5},
{"source": "2", "target": "3", "weight": 2.0}
]
}§Usage
use std::fs::File;
use std::io::Write;
use tempfile::NamedTempFile;
use scirs2_graph::base::Graph;
use scirs2_graph::io::json::{read_json_format, write_json_format};
// Create a temporary file with JSON data
let mut temp_file = NamedTempFile::new().unwrap();
writeln!(temp_file, r#"{{"directed": false, "nodes": [{{"id": "1"}}, {{"id": "2"}}], "edges": [{{"source": "1", "target": "2"}}]}}"#).unwrap();
temp_file.flush().unwrap();
// Read the graph
let graph: Graph<i32, f64> = read_json_format(temp_file.path(), false).unwrap();
assert_eq!(graph.node_count(), 2);
assert_eq!(graph.edge_count(), 1);Structs§
- Json
Edge - JSON representation of a graph edge
- Json
Graph - JSON representation of a complete graph
- Json
Node - JSON representation of a graph node
Functions§
- read_
json_ format - Read an undirected graph from JSON format
- read_
json_ format_ digraph - Read a directed graph from JSON format
- write_
json_ format - Write an undirected graph to JSON format
- write_
json_ format_ digraph - Write a directed graph to JSON format