yog/io/json

JSON format export for graph data exchange.

This module exports graphs to JSON format, suitable for:

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

Options for customizing JSON output.

pub type JsonOptions {
  JsonOptions(
    node_mapper: fn(Int, String) -> json.Json,
    edge_mapper: fn(Int, Int, String) -> json.Json,
  )
}

Constructors

  • JsonOptions(
      node_mapper: fn(Int, String) -> json.Json,
      edge_mapper: fn(Int, Int, String) -> json.Json,
    )

    Arguments

    node_mapper

    Function to convert node ID and data to JSON for the ‘nodes’ array.

    edge_mapper

    Function to convert source, target, and edge weight to JSON for the ‘edges’ array.

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"}
  ]
}
Search Document