yog/io/json
JSON format export for graph data exchange.
This module exports graphs to JSON format, suitable for:
- Interoperability with web applications
- Storage in document databases (MongoDB, CouchDB)
- Visualization libraries (D3.js, Cytoscape.js, vis.js)
- API responses and data exchange
Output Format
The default output format is:
{
"nodes": [
{ "id": 1, "label": "Node A" },
{ "id": 2, "label": "Node B" }
],
"edges": [
{ "source": 1, "target": 2, "weight": "5" }
]
}
Customization
Use JsonOptions with custom node_mapper and edge_mapper functions
to control the exact JSON structure. This allows integration with any
schema required by your frontend or external system.
Example: D3.js Integration
import yog/io/json
// Export for D3.js force simulation
let json_string = json.to_string(graph)
// Use in JavaScript: d3.forceSimulation(JSON.parse(json_string).nodes)
References
Types
Values
pub fn default_json_options() -> JsonOptions
Creates default JSON options.
Nodes are { "id": 1, "label": "Node A" }.
Edges are { "source": 1, "target": 2, "weight": "5" }.
pub fn to_json(
graph: model.Graph(String, String),
options: JsonOptions,
) -> String
Converts a graph to a JSON string compatible with many visualization libraries (e.g., D3.js).
The graph’s node data and edge data must be convertible to strings.
Time Complexity: O(V + E)
Example
import gleam/io
import gleam/json
import yog/model
pub fn main() {
let graph =
model.new(model.Directed)
|> model.add_node(1, "Alice")
|> model.add_node(2, "Bob")
|> model.add_edge(from: 1, to: 2, with: "follows")
let json_string = yog_json.to_json(graph, yog_json.default_json_options())
io.println(json_string)
}
This outputs:
{
"nodes": [
{"id": 1, "label": "Alice"},
{"id": 2, "label": "Bob"}
],
"edges": [
{"source": 1, "target": 2, "weight": "follows"}
]
}