serialize-data-formats

Serialize and deserialize data across common formats: JSON, XML, YAML, Protocol Buffers, MessagePack, Apache Arrow/Parquet. Covers format selection criteria, encoding/decoding patterns, performance tradeoffs, and interoperability. Use when choosing a wire format for API communication, persisting structured data to disk, exchanging data between systems in different languages, optimizing transfer size or parsing speed, or migrating from one serialization format to another.

9 stars

Best use case

serialize-data-formats is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Serialize and deserialize data across common formats: JSON, XML, YAML, Protocol Buffers, MessagePack, Apache Arrow/Parquet. Covers format selection criteria, encoding/decoding patterns, performance tradeoffs, and interoperability. Use when choosing a wire format for API communication, persisting structured data to disk, exchanging data between systems in different languages, optimizing transfer size or parsing speed, or migrating from one serialization format to another.

Teams using serialize-data-formats should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/serialize-data-formats/SKILL.md --create-dirs "https://raw.githubusercontent.com/pjt222/agent-almanac/main/i18n/caveman-lite/skills/serialize-data-formats/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/serialize-data-formats/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How serialize-data-formats Compares

Feature / Agentserialize-data-formatsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Serialize and deserialize data across common formats: JSON, XML, YAML, Protocol Buffers, MessagePack, Apache Arrow/Parquet. Covers format selection criteria, encoding/decoding patterns, performance tradeoffs, and interoperability. Use when choosing a wire format for API communication, persisting structured data to disk, exchanging data between systems in different languages, optimizing transfer size or parsing speed, or migrating from one serialization format to another.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Serialize Data Formats

Select and implement the right data serialization format for your use case, with correct encoding/decoding and performance awareness.

## When to Use

- Choosing a wire format for API communication
- Persisting structured data to disk or object storage
- Exchanging data between systems written in different languages
- Optimizing data transfer size or parsing speed
- Migrating from one serialization format to another

## Inputs

- **Required**: Data structure to serialize (schema or example)
- **Required**: Use case (API, storage, streaming, analytics)
- **Optional**: Performance requirements (size, speed, schema enforcement)
- **Optional**: Target language/runtime constraints
- **Optional**: Human readability requirements

## Procedure

### Step 1: Select the Right Format

| Format | Human Readable | Schema | Size | Speed | Best For |
|--------|---------------|--------|------|-------|----------|
| JSON | Yes | Optional (JSON Schema) | Medium | Medium | REST APIs, config, broad interop |
| XML | Yes | XSD, DTD | Large | Slow | Enterprise/legacy, SOAP, documents |
| YAML | Yes | Optional | Medium | Slow | Config files, CI/CD, Kubernetes |
| Protocol Buffers | No | Required (.proto) | Small | Fast | gRPC, microservices, mobile |
| MessagePack | No | None | Small | Fast | Real-time, embedded, Redis |
| Arrow/Parquet | No | Built-in | Very Small | Very Fast | Analytics, columnar queries, data lakes |

Decision tree:
1. **Need human editing?** → YAML (config) or JSON (data)
2. **Need strict schema + fast RPC?** → Protocol Buffers
3. **Need smallest wire size?** → MessagePack or Protobuf
4. **Need columnar analytics?** → Apache Parquet
5. **Need in-memory interchange?** → Apache Arrow
6. **Legacy enterprise integration?** → XML

**Got:** Format selected with documented rationale matching use case requirements.
**If fail:** With conflicting requirements (e.g., human-readable AND fast), prioritize the primary use case and note the tradeoff.

### Step 2: Implement JSON Serialization

```python
import json
from datetime import datetime, date
from dataclasses import dataclass, asdict

@dataclass
class Measurement:
    sensor_id: str
    value: float
    unit: str
    timestamp: datetime

# Custom encoder for non-standard types
class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        if isinstance(obj, date):
            return obj.isoformat()
        if isinstance(obj, bytes):
            import base64
            return base64.b64encode(obj).decode('ascii')
        return super().default(obj)

# Serialize
measurement = Measurement("sensor-01", 23.5, "celsius", datetime.now())
json_str = json.dumps(asdict(measurement), cls=CustomEncoder, indent=2)

# Deserialize
data = json.loads(json_str)
```

```r
# R: JSON with jsonlite
library(jsonlite)

# Serialize
df <- data.frame(sensor_id = "sensor-01", value = 23.5, unit = "celsius")
json_str <- jsonlite::toJSON(df, auto_unbox = TRUE, pretty = TRUE)

# Deserialize
df_back <- jsonlite::fromJSON(json_str)
```

**Got:** Round-trip serialization preserves all data types accurately.
**If fail:** If a type is lost (e.g., dates become strings), add explicit type conversion in the deserialization step.

### Step 3: Implement Protocol Buffers

Define the schema (`.proto` file):

```protobuf
syntax = "proto3";
package sensors;

message Measurement {
  string sensor_id = 1;
  double value = 2;
  string unit = 3;
  int64 timestamp_ms = 4;  // Unix milliseconds
}

message MeasurementBatch {
  repeated Measurement measurements = 1;
}
```

Generate and use:

```bash
# Generate Python code
protoc --python_out=. sensors.proto

# Generate Go code
protoc --go_out=. sensors.proto
```

```python
from sensors_pb2 import Measurement, MeasurementBatch
import time

# Serialize
m = Measurement(
    sensor_id="sensor-01",
    value=23.5,
    unit="celsius",
    timestamp_ms=int(time.time() * 1000)
)
binary = m.SerializeToString()  # Compact binary

# Deserialize
m2 = Measurement()
m2.ParseFromString(binary)
```

**Got:** Binary output 3-10x smaller than equivalent JSON.
**If fail:** If protoc is unavailable, use a language-native protobuf library (e.g., `betterproto` for Python).

### Step 4: Implement MessagePack

```python
import msgpack
from datetime import datetime

# Custom packing for datetime
def encode_datetime(obj):
    if isinstance(obj, datetime):
        return {"__datetime__": True, "s": obj.isoformat()}
    return obj

def decode_datetime(obj):
    if "__datetime__" in obj:
        return datetime.fromisoformat(obj["s"])
    return obj

data = {"sensor_id": "sensor-01", "value": 23.5, "ts": datetime.now()}

# Serialize (smaller than JSON, faster than JSON)
packed = msgpack.packb(data, default=encode_datetime)

# Deserialize
unpacked = msgpack.unpackb(packed, object_hook=decode_datetime, raw=False)
```

**Got:** MessagePack output is 15-30% smaller than JSON for typical payloads.
**If fail:** If a language lacks MessagePack support, fall back to JSON with compression (gzip).

### Step 5: Implement Apache Parquet (Columnar)

```python
import pyarrow as pa
import pyarrow.parquet as pq
import pandas as pd

# Create data
df = pd.DataFrame({
    "sensor_id": ["s-01", "s-02", "s-01", "s-03"] * 1000,
    "value": [23.5, 18.2, 24.1, 19.8] * 1000,
    "unit": ["celsius"] * 4000,
    "timestamp": pd.date_range("2025-01-01", periods=4000, freq="min")
})

# Write Parquet (columnar, compressed)
table = pa.Table.from_pandas(df)
pq.write_table(table, "measurements.parquet", compression="snappy")

# Read Parquet (can read specific columns without loading all data)
table_back = pq.read_table("measurements.parquet", columns=["sensor_id", "value"])
df_subset = table_back.to_pandas()
```

```r
# R: Parquet with arrow
library(arrow)

# Write
df <- data.frame(sensor_id = rep("s-01", 1000), value = rnorm(1000))
arrow::write_parquet(df, "measurements.parquet")

# Read (with column selection — only reads selected columns from disk)
df_back <- arrow::read_parquet("measurements.parquet", col_select = c("value"))
```

**Got:** Parquet files 5-20x smaller than CSV for typical tabular data.
**If fail:** If Arrow is unavailable, use `fastparquet` (Python) or CSV with gzip as fallback.

### Step 6: Compare Performance

Run benchmarks for your specific data and use case:

```python
import json, msgpack, time
import pyarrow as pa, pyarrow.parquet as pq

data = [{"id": i, "value": i * 0.1, "label": f"item-{i}"} for i in range(10000)]

# JSON
start = time.perf_counter()
json_bytes = json.dumps(data).encode()
json_time = time.perf_counter() - start

# MessagePack
start = time.perf_counter()
msgpack_bytes = msgpack.packb(data)
msgpack_time = time.perf_counter() - start

print(f"JSON:    {len(json_bytes):>8} bytes, {json_time*1000:.1f} ms")
print(f"MsgPack: {len(msgpack_bytes):>8} bytes, {msgpack_time*1000:.1f} ms")
```

**Got:** Benchmark results guide format selection for production use.
**If fail:** If performance is insufficient for any format, consider compression (zstd, snappy) as an orthogonal optimization.

## Validation

- [ ] Selected format matches use case requirements (documented rationale)
- [ ] Round-trip serialization preserves all data types
- [ ] Edge cases handled: empty collections, null/None values, Unicode, large numbers
- [ ] Performance benchmarked for representative payload sizes
- [ ] Error handling for malformed input (graceful failures, not crashes)
- [ ] Schema documented (JSON Schema, .proto, or equivalent)

## Pitfalls

- **Floating-point precision**: JSON represents all numbers as IEEE 754 doubles. Use string encoding for financial/decimal precision.
- **Date/time handling**: JSON has no native datetime type. Always document the format (ISO 8601) and timezone handling.
- **Schema evolution**: Adding or removing fields can break consumers. Protobuf handles this well; JSON requires careful versioning.
- **Binary data in JSON**: Base64 encoding inflates binary data by ~33%. Use a binary format for binary-heavy payloads.
- **YAML security**: YAML parsers may execute arbitrary code via `!!python/object` tags. Always use safe loaders.

## Related Skills

- `design-serialization-schema` — schema design, versioning, and evolution strategies
- `implement-pharma-serialisation` — pharmaceutical serialisation (different domain, same naming)
- `create-quarto-report` — data output formatting for reports

Related Skills

version-ml-data

9
from pjt222/agent-almanac

Version machine learning datasets using DVC (Data Version Control) with remote storage backends, build reproducible data pipelines with dependency tracking, integrate with Git workflows, and ensure data lineage for model reproducibility. Use when versioning large datasets that do not fit in Git, tracking data changes alongside code changes, ensuring ML experiment reproducibility, sharing datasets across team members, or auditing data lineage for compliance requirements.

review-data-analysis

9
from pjt222/agent-almanac

Review a data analysis for quality, correctness, and reproducibility. Covers data quality assessment, assumption checking, model validation, data leakage detection, and reproducibility verification. Use when reviewing a colleague's analysis before publication, validating an ML pipeline before production deployment, auditing a report for regulatory or business decision-making, or performing a second-analyst review in a regulated environment.

monitor-data-integrity

9
from pjt222/agent-almanac

Design and operate a data integrity monitoring programme based on ALCOA+ principles. Covers detective controls, audit trail review schedules, anomaly detection patterns (off-hours activity, sequential modifications, bulk changes), metrics dashboards, investigation triggers, and escalation matrix definition. Use when establishing a data integrity monitoring programme for GxP systems, preparing for inspections where data integrity is a focus area, after a data integrity incident requiring enhanced monitoring, or when implementing MHRA, WHO, or PIC/S guidance.

label-training-data

9
from pjt222/agent-almanac

Set up systematic data labeling workflows using Label Studio or similar tools. Implement quality controls, measure inter-annotator agreement, manage labeler teams, and integrate labeled data into ML training pipelines. Use when starting a supervised ML project that requires labeled training data, when model performance is limited by insufficient labeled examples, when labeling text, images, audio, or video, or when implementing active learning to prioritize the most valuable examples.

skill-name-here

9
from pjt222/agent-almanac

One to three sentences describing what this skill accomplishes, followed by key activation triggers. This field is the primary mechanism agents use to decide whether to activate the skill — it is read during discovery before the full body is loaded. Start with a verb. Include the most important "when to use" conditions inline. Max 1024 characters.

write-vignette

9
from pjt222/agent-almanac

Create R package vignettes using R Markdown or Quarto. Covers vignette setup, YAML configuration, code chunk options, building and testing, and CRAN requirements for vignettes. Use when adding a Getting Started tutorial, documenting complex workflows spanning multiple functions, creating domain-specific guides, or when CRAN submission requires user-facing documentation beyond function help pages.

write-validation-documentation

9
from pjt222/agent-almanac

Write IQ/OQ/PQ validation documentation for computerized systems in regulated environments. Covers protocols, reports, test scripts, deviation handling, and approval workflows. Use when validating R or other software for regulated use, preparing for a regulatory audit, documenting qualification of computing environments, or creating and updating validation protocols and reports for new or re-qualified systems.

write-testthat-tests

9
from pjt222/agent-almanac

Write comprehensive testthat (edition 3) tests for R package functions. Covers test organization, expectations, fixtures, mocking, snapshot tests, parameterized tests, and achieving high coverage. Use when adding tests for new package functions, increasing test coverage for existing code, writing regression tests for bug fixes, or setting up test infrastructure for a package that lacks it.

write-standard-operating-procedure

9
from pjt222/agent-almanac

Write a GxP-compliant Standard Operating Procedure (SOP). Covers regulatory SOP template structure (purpose, scope, definitions, responsibilities, procedure, references, revision history), approval workflow design, periodic review scheduling, and operational procedures for system use. Use when a new validated system requires operational procedures, when existing informal procedures need formalisation, when an audit finding cites missing procedures, when a change control triggers SOP updates, or when periodic review identifies outdated procedural content.

write-roxygen-docs

9
from pjt222/agent-almanac

Write roxygen2 documentation for R package functions, datasets, and classes. Covers all standard tags, cross-references, examples, and generating NAMESPACE entries. Follows tidyverse documentation style. Use when adding documentation to new exported functions, documenting internal helpers or datasets, documenting S3/S4/R6 classes and methods, or fixing documentation-related R CMD check notes.

write-incident-runbook

9
from pjt222/agent-almanac

Create structured incident runbooks with diagnostic steps, resolution procedures, escalation paths, and communication templates for effective incident response. Use when documenting response procedures for recurring alerts, standardizing incident response across an on-call rotation, reducing MTTR with clear diagnostic steps, creating training materials for new team members, or linking alert annotations directly to resolution procedures.

write-helm-chart

9
from pjt222/agent-almanac

Create production-ready Helm charts for Kubernetes application deployment with templating, values management, chart dependencies, hooks, and testing. Covers chart structure, Go template syntax, values.yaml design, chart repositories, versioning, and best practices for maintainable and reusable charts. Use when packaging a Kubernetes application for repeatable deployments, parameterizing manifests for multiple environments, managing complex multi-component applications with dependencies, or standardizing deployment practices with versioned rollback capability across teams.