Module json

Module json 

Source
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§

JsonEdge
JSON representation of a graph edge
JsonGraph
JSON representation of a complete graph
JsonNode
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