Serialize Three.js Object3D Hierarchy to JSON

Serializing a Three.js scene or Object3D hierarchy into a standard JSON format allows you to save, transmit, or dynamically load 3D assets. This article explains how to use the built-in toJSON() method in Three.js to export an entire object hierarchy—including its children, materials, textures, and geometries—into a single JSON object, and how to reconstruct it later using the ObjectLoader.

Using the toJSON() Method

Every class inheriting from THREE.Object3D (including THREE.Scene, THREE.Group, and THREE.Mesh) inherits the toJSON() method. When called on a parent object, this method recursively serializes the entire node hierarchy, along with all associated assets.

Here is the basic implementation to serialize an object hierarchy:

// Assume 'myGroup' is a THREE.Group containing meshes, lights, and materials
const jsonObject = myGroup.toJSON();

// Convert the JSON object to a string to save or send to a server
const jsonString = JSON.stringify(jsonObject);

console.log(jsonString);

Structure of the Exported JSON

The output of toJSON() is a standard JavaScript object containing several key-value pairs designed to prevent duplication of assets. The main components of the exported structure include:

Loading the Serialized Object Back Into Three.js

To reconstruct the serialized JSON back into functional Three.js objects, use the THREE.ObjectLoader class. This loader parses the JSON, reinstantiates all geometries, materials, and textures, and reconstructs the original object hierarchy.

import * as THREE from 'three';

// Instantiate the ObjectLoader
const loader = new THREE.ObjectLoader();

// Parse the JSON object (not the string, pass the parsed object)
const restoredGroup = loader.parse(jsonObject);

// Add the restored hierarchy back into your active scene
scene.add(restoredGroup);

If you saved the JSON output as a physical file (e.g., model.json), you can load it directly via a URL:

const loader = new THREE.ObjectLoader();

loader.load(
    'path/to/model.json',
    function (obj) {
        scene.add(obj);
    },
    function (xhr) {
        console.log((xhr.loaded / xhr.total * 100) + '% loaded');
    },
    function (err) {
        console.error('An error occurred while loading the JSON');
    }
);