# How the Dump Command Serializes Office Documents to JSON for Round-Trip Replay in OfficeCLI

> Learn how the OfficeCLI dump command serializes Office documents to JSON for lossless round-trip replay. Reconstruct identical documents with this compact format.

- Repository: [OfficeAI/OfficeCLI](https://github.com/iofficeai/OfficeCLI)
- Tags: internals
- Published: 2026-08-03

---

**The `dump` command exports any Office document to a compact, single-line JSON array that `batch run` can replay to reconstruct an identical copy, making it a lossless serialization format for round-trip document workflows.**

The **dump command** is OfficeCLI's core mechanism for converting `.docx`, `.pptx`, and `.xlsx` files into a portable, replayable format. According to the iOfficeAI/OfficeCLI source code, this process creates a **batch script** that captures every element, property, and embedded resource needed to recreate the document byte-for-byte. Understanding how this JSON serialization works is essential for building reliable document automation pipelines.

## How the Dump Command Processes Documents

The serialization pipeline in [`CommandBuilder.Dump.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Dump.cs) follows eight distinct stages, each handling a specific aspect of document-to-JSON conversion.

### Step 1: Parse CLI Arguments

Lines 15-30 in [`CommandBuilder.Dump.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Dump.cs) define the command's argument structure:

```bash
officecli dump <file> <path> [--format <format>] [--out <file>] [--json]

```

- **`file`** – Path to the source document
- **`path`** – OOXML part path to dump (use `/` for the entire document)
- **`--format`** – Optional format specifier
- **`--out`** – Output destination (`-` for stdout, or a file path)
- **`--json`** – Wrap output in the standard success envelope

### Step 2: Validate File Extension

Lines 50-66 enforce strict file type validation. The command rejects unsupported extensions and verifies the file exists before processing:

```csharp
// Pseudocode representing the validation logic
if (!file.Exists) throw FileNotFoundException();
if (!extension.IsOneOf(".docx", ".pptx", ".xlsx")) throw NotSupportedException();

```

### Step 3: Route to Resident Process (If Active)

Lines 68-79 implement **resident forwarding**. If a resident process already holds the file open, the dump request routes through it instead of creating a new handler. This prevents "file in use" conflicts on long-running automation servers.

### Step 4: Open Document Handler

Lines 99-105 create a **read-only handler** via `DocumentHandlerFactory.Open`. The factory returns:

- **`WordHandler`** for `.docx` files
- **`PowerPointHandler`** for `.pptx` files
- **`ExcelHandler`** for `.xlsx` files

### Step 5: Emit Batch Operations

Each handler delegates to a specialized **batch emitter** that walks the OOXML part tree. The emitters generate `List<BatchItem>` objects plus **warnings** for any unsupported elements:

| Document Type | Emitter Method | Code Location |
|-------------|----------------|---------------|
| Word | `WordBatchEmitter.EmitWordWithWarnings` | lines 108-124 |
| PowerPoint | `PptxBatchEmitter.EmitPptx` | lines 135-154 |
| Excel | `ExcelBatchEmitter.EmitExcel` | lines 158-175 |

These emitters extract:
- Element types and property values
- Text content and formatting
- Embedded images and OLE objects
- Chart data and theme resources
- Structural ordering information

### Step 6: Inject Metadata Header

Line 186 inserts a **`BatchCompat.MetaItem()`** header that records:

- **Dump version** – Ensures compatibility with future `batch run` implementations
- **Line-break handling** – Uses vertical tab (`'\v'`) instead of newline (`'\n'`) to keep the JSON single-line

### Step 7: Serialize to Compact JSON

Lines 187-188 perform the final serialization using **`BatchJsonContext`**, a **source-generated JSON serializer context**. This produces:

- **Single-line JSON array** – No pretty-printing, minimal whitespace
- **Canonical wire format** – Guaranteed consistent output across platforms

### Step 8: Handle Output Destination

Lines 191-225 branch on the `--out` and `--json` flags:

| Flags | Behavior |
|-------|----------|
| `--out -` | Write raw JSON to **stdout** |
| `--out <file>` | Write JSON to file with trailing newline |
| `--json` | Wrap in standard envelope: `{ success:true, data:"...", warnings:[...] }` |

## Round-Trip Mechanics: Export → JSON → Re-Import

The **dump command JSON format** enables three-phase round-trip workflows:

1. **Export Phase** – `dump` generates a complete JSON description of the document subtree
2. **Transport Phase** – The single-line JSON can be stored, transferred, or versioned
3. **Re-import Phase** – `batch run` executes each `BatchItem` to reconstruct the original

### Idempotency Guarantees

Because the dump captures **all referenced parts** (including images, fonts, and theme resources) and the meta item conveys versioning information, a properly executed round-trip yields **byte-wise identical documents** (subject to OOXML canonicalization rules). Unsupported elements are deliberately omitted and reported as warnings rather than causing silent data loss.

## Practical Code Examples

### Basic Dump to File

Dump an entire PowerPoint presentation for later replay:

```bash
officecli dump myPresentation.pptx / --out presentation.json

```

The resulting [`presentation.json`](https://github.com/iOfficeAI/OfficeCLI/blob/main/presentation.json) contains a single-line array ready for `batch run`.

### Programmatic Consumption with Envelope

For API integration, request the standard JSON envelope:

```bash
officecli dump mySpreadsheet.xlsx / --json --out -

```

Output format:

```json
{
  "success": true,
  "data": "[{\"op\":\"add\",\"path\":\"/...\"},...]",
  "warnings": [{"message":"skipped legacy shape","code":"unsupported_element"}]
}

```

### Complete Round-Trip Workflow

```bash

# Phase 1: Export to JSON

officecli dump report.docx / --out report.dump.json

# Phase 2: Create blank target document

officecli create fresh.docx

# Phase 3: Replay dump to reconstruct

officecli batch run --input report.dump.json --doc fresh.docx

```

After execution, `fresh.docx` matches `report.docx` content and structure.

### Resident-Enabled Dump for Large Files

Avoid file locking on automation servers:

```bash
officecli resident start &
officecli dump large.docx / --out large.json  # automatically routed through resident

```

## Key Source Files

Understanding these files provides full visibility into the JSON serialization pipeline:

- **[`src/officecli/CommandBuilder.Dump.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Dump.cs)** – Main command implementation, orchestrating all eight processing steps
- **[`src/officecli/Handlers/Word/WordBatchEmitter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Handlers/Word/WordBatchEmitter.cs)** – Word-specific OOXML tree walking and `BatchItem` generation
- **[`src/officecli/Handlers/PowerPoint/PowerPointBatchEmitter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Handlers/PowerPoint/PowerPointBatchEmitter.cs)** – PowerPoint-specific emitter logic
- **[`src/officecli/Handlers/Excel/ExcelBatchEmitter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Handlers/Excel/ExcelBatchEmitter.cs)** – Excel-specific emitter logic
- **[`src/officecli/Core/OutputFormatter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/OutputFormatter.cs)** – Envelope wrapping and warning injection for `--json` mode
- **[`src/officecli/Core/BatchCompat.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/BatchCompat.cs)** – Metadata header generation with version stamps and line-break semantics

## Summary

- The **dump command** creates replayable JSON batch scripts through an eight-stage pipeline in [`CommandBuilder.Dump.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Dump.cs)
- **Document-specific emitters** (`WordBatchEmitter`, `PptxBatchEmitter`, `ExcelBatchEmitter`) extract complete OOXML part trees
- **`BatchJsonContext`** serializes to canonical single-line JSON for consistent wire format
- The **meta item** at line 186 ensures version compatibility and proper line-break handling
- **Round-trip replay** via `batch run` reconstructs byte-identical documents when warnings are heeded
- **Resident routing** prevents file locking conflicts in server environments

## Frequently Asked Questions

### What makes the dump command JSON format "round-trip safe"?

The format captures **complete document state** including embedded resources, ordering, and metadata. The `BatchItem` sequence is deterministic, and the meta header ensures `batch run` interprets soft line breaks correctly. Warnings flag any unsupported elements so you know exactly what won't round-trip.

### Why does the JSON output use a single line instead of pretty-printing?

**Single-line JSON** (produced by `BatchJsonContext` at lines 187-188) serves two purposes: it minimizes payload size for network transfer, and it prevents newline-sensitive tooling from corrupting the batch structure. The vertical tab (`'\v'`) convention preserves readable breaks internally without introducing actual newline characters.

### Can I edit the dumped JSON before replaying it?

Yes. The `BatchItem` array is human-readable and follows predictable patterns for `op` (operation), `path` (target location), and `value` (payload). Modifying values or reordering items works for **content changes**, but structural edits risk breaking OOXML validity. Always validate heavily modified dumps in a test environment.

### What happens if the resident process isn't running?

The dump command **gracefully falls back** to direct file handling. Lines 68-79 check for an active resident; if none exists, the code proceeds to `DocumentHandlerFactory.Open` at line 99. Resident mode is purely an optimization for concurrent access scenarios, not a hard dependency.