How to Export a treelib Tree to JSON: Complete Guide with Code Examples

Use the Tree.to_json() method to serialize any treelib tree into a JSON string, optionally embedding node data with with_data=True and controlling child node ordering via sort and reverse parameters.

The treelib library provides native JSON serialization capabilities through the Tree class implemented in treelib/tree.py. When you need to export a treelib tree to JSON for persistent storage, API transmission, or cross-platform data exchange, the built-in to_json() method recursively traverses the hierarchy and generates a standardized JSON representation without requiring external dependencies.

Understanding the Tree.to_json() Method

The JSON export functionality centers on a single method that delegates to an internal dictionary conversion routine.

Method Signature and Core Implementation

According to the source code in treelib/tree.py (lines 1981–1984), the method signature is:

def to_json(self, with_data: bool = False, sort: bool = True, reverse: bool = False):

The implementation performs two distinct operations. First, it calls self.to_dict() (defined at lines 1960–1979) to build a nested dictionary mirroring the tree hierarchy. Second, it returns json.dumps(self.to_dict(...)) (lines 2065–2067) to produce the final string output.

Key parameters control the output:

  • with_data – When set to True, includes each node's .data attribute in the JSON payload. Defaults to False to minimize payload size.
  • sort – Sorts children by their tag strings before serialization when True (default).
  • reverse – Inverts the sort order when True, working in conjunction with the sort parameter.

Exporting treelib Trees to JSON: Practical Examples

Basic Export Without Node Data

For structure-only exports where you need the hierarchy but not the payload, call to_json() with default parameters:

from treelib import Tree

tree = Tree()
tree.create_node("Root", "root")
tree.create_node("Child A", "a", parent="root")
tree.create_node("Child B", "b", parent="root")

# Export structure only

json_str = tree.to_json()
print(json_str)

This generates a lean JSON object mapping node tags to their children:

{"Root": {"children": [{"Child A": {}}, {"Child B": {}}]}}

Exporting With Node Data

To preserve the .data attributes attached to each node, set with_data=True as documented in the method docstring (lines 1989–1997):


# Create a node with associated data

tree.create_node(
    "Data Node", "data",
    parent="root",
    data={"type": "important", "value": 42}
)

# Export with data included

json_with_data = tree.to_json(with_data=True)
print(json_with_data)

The resulting JSON includes a "data" key for each node containing its payload dictionary.

Pretty-Printing JSON Output

The treelib source provides a pattern for readable formatting in examples/json_trees.py (lines 2055–2059). Since to_json() returns a compact string, parse and re-serialize with standard library indentation:

import json

raw_json = tree.to_json(with_data=True)
pretty_json = json.dumps(json.loads(raw_json), indent=2, ensure_ascii=False)

print(pretty_json)

This approach maintains compatibility with treelib's export format while adding human-readable whitespace.

Saving JSON to Disk

For persistent storage, write the generated string directly to a file as demonstrated in examples/save_tree2file.py (lines 84–92):

json_output = tree.to_json(with_data=True)

with open("my_tree.json", "w", encoding="utf-8") as f:
    f.write(json_output)

print("Tree saved to my_tree.json")

This pattern handles trees of any depth, preserving the complete hierarchical structure for later retrieval or version control.

Reconstructing Trees from Exported JSON

The repository provides a complete round-trip example in examples/json_trees.py (lines 94–130) demonstrating how to parse the exported JSON and reconstruct a functional Tree instance. While treelib does not provide a built-in from_json() method in the core library, the JSON structure follows a predictable schema where each key represents a node tag and each value contains optional data and children arrays, enabling straightforward recursive reconstruction.

Summary

  • Use Tree.to_json() in treelib/tree.py to convert any tree to a JSON string in a single call.
  • Control data inclusion with the with_data parameter to toggle serialization of node payloads.
  • Manage node ordering via sort and reverse parameters to enforce deterministic output.
  • Persist results by writing the returned string to files or transmitting via network APIs.
  • Reconstruct trees by parsing the JSON and recursively creating nodes following the schema documented in examples/json_trees.py.

Frequently Asked Questions

How do I include node data when exporting treelib to JSON?

Pass with_data=True to the to_json() method. By default, the method excludes node data to produce smaller payloads, but setting this parameter embeds each node's .data dictionary directly into the JSON structure alongside the children array.

Can I control the order of nodes in the JSON output?

Yes. The sort parameter (default True) alphabetically orders children by their tag strings, while reverse=True inverts that alphabetical order. These parameters affect the array order within the children keys of the exported JSON object.

How do I save the JSON output to a file?

Call tree.to_json() to obtain the string, then write it using standard Python file I/O. The repository's examples/save_tree2file.py demonstrates this pattern, showing how to export with with_data=True and persist the result to disk with UTF-8 encoding.

Is it possible to reconstruct a tree from the exported JSON?

While treelib does not ship with a built-in from_json() class method, the JSON schema produced by to_json() follows a predictable nested structure where keys are node tags and values contain optional data and children. The examples/json_trees.py file provides a complete reference implementation showing how to parse this JSON and recursively rebuild a Tree instance using create_node().

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 →