How to Export the code-graph-rag Graph to JSON: CLI and Python API Guide

You can export the code-graph-rag graph to JSON using the built-in CLI command python -m codebase_rag.graph_cli export or programmatically via the GraphLoader.to_json() method in codebase_rag.graph_loader.

The vitali87/code-graph-rag repository provides tools for building graph models from codebases and serializing them into JSON format. Whether you need to integrate the graph data into external tools or store it for analysis, the library offers both a command-line interface and a Python API to handle JSON export. This guide covers the specific steps to export your graphs using the exact source files and methods implemented in the codebase.

Using the CLI to Export to JSON

The primary entry point for JSON export is the export subcommand in codebase_rag/graph_cli.py. This module handles argument parsing, validates file paths, and coordinates the export process.

To export a graph from the command line:

python -m codebase_rag.graph_cli export \
    --graph-file path/to/graph.graphml \
    --output path/to/exported_graph.json \
    --pretty

The CLI accepts three key arguments:

  • --graph-file: Path to the source graph (supports GraphML, GraphML-GQL, and other formats)
  • --output: Destination path for the JSON file
  • --pretty: Optional flag that writes JSON with indent=2 for readability

Error Handling in CLI Mode

If the export encounters an I/O error or malformed source graph, the CLI raises the EXPORT_FAILED exception defined in codebase_rag/tool_errors.py and prints the user-visible message CLI_ERR_EXPORT_FAILED from codebase_rag/constants/cli.py.

Programmatic Export with the Python API

For custom workflows, use the GraphLoader class in codebase_rag/graph_loader.py. The load_graph() function returns a GraphLoader instance containing the to_json() method.

Basic programmatic export:

from pathlib import Path
from codebase_rag.graph_loader import load_graph
import json

# Load the graph file

graph_path = Path("path/to/graph.graphml")
graph = load_graph(str(graph_path))

# Convert to JSON-serializable dict

graph_json = graph.to_json()

# Write to file

output_path = Path("path/to/output.json")
with output_path.open("w", encoding="utf-8") as f:
    json.dump(graph_json, f, indent=2)

The GraphLoader builds an internal representation of nodes, relationships, and metadata before serialization. You can inspect the graph using helper methods like summary() or find_nodes_by_label() before calling to_json().

Adapting the Example Script

The repository includes examples/graph_export_example.py, which demonstrates loading a graph and printing a summary. Modify the _perform_graph_analysis function to add JSON export:

import json
from pathlib import Path

def _perform_graph_analysis(graph_file: str) -> None:
    graph = load_graph(graph_file)
    # Existing summary logging...

    
    # Export to JSON

    json_path = Path(graph_file).with_suffix(".json")
    with json_path.open("w", encoding="utf-8") as fp:
        json.dump(graph.to_json(), fp, indent=2)

Running the modified script produces a sidecar JSON file alongside your graph data.

Architecture and Implementation Details

The JSON export functionality spans several layers:

CLI Layer (codebase_rag/graph_cli.py): Parses the export subcommand, validates --graph-file and --output arguments, and prints status messages using constants from codebase_rag/constants/cli.py (such as CLI_MSG_CONNECTING_MEMGRAPH).

Export Logic (codebase_rag/graph_loader.py): The load_graph() function instantiates GraphLoader, which implements the to_json() method to produce a serializable Python dictionary containing nodes, relationships, and graph metadata.

Error Management (codebase_rag/constants/cli.py and codebase_rag/tool_errors.py): Defines error templates and the EXPORT_FAILED exception used when serialization fails.

Summary

  • Use the CLI (python -m codebase_rag.graph_cli export) for quick exports with --graph-file, --output, and optional --pretty formatting.
  • Use the Python API (codebase_rag.graph_loader.load_graph().to_json()) for custom integration into data pipelines.
  • Key source files include codebase_rag/graph_cli.py for command-line entry and codebase_rag/graph_loader.py for the core serialization logic.
  • Error handling relies on EXPORT_FAILED exceptions and CLI constants for user-friendly error messages.
  • Example code in examples/graph_export_example.py provides a template for custom export scripts.

Frequently Asked Questions

What input formats can be exported to JSON?

The GraphLoader in codebase_rag/graph_loader.py accepts multiple graph formats including GraphML and GraphML-GQL. The load_graph() function parses these formats into an internal model before to_json() serializes them to JSON.

Where is the export logic implemented?

The core export logic resides in codebase_rag/graph_loader.py within the GraphLoader class, specifically the to_json() method. The CLI wrapper that invokes this logic is located in codebase_rag/graph_cli.py.

How do I handle export errors?

The CLI catches exceptions and raises EXPORT_FAILED from codebase_rag/tool_errors.py, displaying the message defined in CLI_ERR_EXPORT_FAILED from codebase_rag/constants/cli.py. In Python code, wrap the load_graph() or file write operations in try-except blocks to handle EXPORT_FAILED or standard I/O errors.

Can I customize the JSON output format?

Yes. When using the Python API, you control the final JSON formatting through json.dump() parameters. Use indent=2 for pretty-printing (equivalent to the CLI's --pretty flag) or indent=None for compact output. The to_json() method returns a standard Python dictionary, allowing you to modify the data structure before serialization if needed.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →