This guide provides practical CBOR implementation examples across multiple programming languages. Each example demonstrates encoding data to CBOR format and decoding it back, with production-ready error handling and best practices.
CBOR (Concise Binary Object Representation) provides efficient binary encoding for structured data. These examples cover common use cases including IoT sensor data, API responses, configuration storage, and binary data handling. All code samples are tested and ready for integration.
Test these examples using our online tools: JSON to CBOR converter,CBOR to JSON decoder, andCBOR validator.
JavaScript / Node.js Examples
Example 1: Basic Encoding and Decoding
Using the cbor-x library for high-performance CBOR encoding/decoding:
Installation:
npm install cbor-xconst { encode, decode } = require('cbor-x');
// Data to encode
const sensorData = {
deviceId: 'sensor-001',
temperature: 22.5,
humidity: 65,
timestamp: new Date('2025-12-24T10:30:00Z'),
readings: [20.1, 21.3, 22.5, 23.1],
status: 'active',
metadata: {
location: 'Building A',
floor: 3
}
};
// Encode to CBOR
const cborBuffer = encode(sensorData);
console.log('CBOR size:', cborBuffer.length, 'bytes');
console.log('CBOR hex:', cborBuffer.toString('hex'));
// Decode from CBOR
const decoded = decode(cborBuffer);
console.log('Decoded:', decoded);
// Verify data integrity
console.log('Temperature match:', decoded.temperature === 22.5);
console.log('Device ID match:', decoded.deviceId === 'sensor-001');Output: CBOR size: 145 bytes (JSON would be ~220 bytes)
Performance: Encodes/decodes in <1ms for typical payloads
Example 2: Handling Binary Data
CBOR efficiently handles binary data without base64 encoding:
const { encode, decode } = require('cbor-x');
const fs = require('fs');
// Example: Encoding an image with metadata
const imageBuffer = fs.readFileSync('thumbnail.jpg');
const imageData = {
filename: 'thumbnail.jpg',
mimetype: 'image/jpeg',
size: imageBuffer.length,
data: imageBuffer, // Binary data stored directly
uploadedAt: new Date(),
tags: ['product', 'thumbnail']
};
// Encode to CBOR
const cborEncoded = encode(imageData);
// Size comparison
const jsonWithBase64 = JSON.stringify({
...imageData,
data: imageBuffer.toString('base64')
});
console.log('CBOR size:', cborEncoded.length);
console.log('JSON size:', jsonWithBase64.length);
console.log('CBOR savings:',
((jsonWithBase64.length - cborEncoded.length) /
jsonWithBase64.length * 100).toFixed(1) + '%');
// Decode and verify
const decoded = decode(cborEncoded);
console.log('Image restored:', Buffer.compare(decoded.data, imageBuffer) === 0);Advantage: 33% smaller than JSON with base64. No encoding/decoding overhead.
Python Examples
Example 3: Python CBOR Implementation
Using the cbor2 library:
Installation:
pip install cbor2import cbor2
from datetime import datetime
import json
# IoT sensor data
sensor_data = {
'device_id': 'temp-sensor-42',
'temperature': 23.7,
'humidity': 58,
'pressure': 1013.25,
'timestamp': datetime.now(),
'location': {
'latitude': 37.7749,
'longitude': -122.4194,
'altitude': 15.5
},
'battery_level': 87,
'status': 'online'
}
# Encode to CBOR
cbor_bytes = cbor2.dumps(sensor_data)
print(f"CBOR size: {len(cbor_bytes)} bytes")
# Compare with JSON
json_str = json.dumps(sensor_data, default=str)
json_bytes = json_str.encode('utf-8')
print(f"JSON size: {len(json_bytes)} bytes")
print(f"Savings: {(1 - len(cbor_bytes)/len(json_bytes))*100:.1f}%")
# Decode from CBOR
decoded = cbor2.loads(cbor_bytes)
print(f"\nDecoded device: {decoded['device_id']}")
print(f"Temperature: {decoded['temperature']}°C")
print(f"Location: {decoded['location']['latitude']}, {decoded['location']['longitude']}")
# Verify data integrity
assert decoded['temperature'] == sensor_data['temperature']
assert decoded['device_id'] == sensor_data['device_id']
print("\nData integrity verified ✓")Example 4: File Storage with CBOR
Using CBOR for efficient configuration file storage:
import cbor2
# Application configuration
config = {
'app_name': 'IoT Gateway',
'version': '2.1.0',
'database': {
'host': 'localhost',
'port': 5432,
'name': 'sensor_db',
'pool_size': 20
},
'mqtt': {
'broker': 'mqtt.example.com',
'port': 1883,
'topics': ['sensors/+/data', 'alerts/#'],
'qos': 1
},
'features': {
'data_compression': True,
'encryption': True,
'batch_processing': True
},
'thresholds': {
'temperature_max': 35.0,
'humidity_max': 80,
'alert_levels': [25, 50, 75, 90]
}
}
# Save configuration to CBOR file
with open('config.cbor', 'wb') as f:
cbor2.dump(config, f)
print("Configuration saved to config.cbor")
# Load configuration from CBOR file
with open('config.cbor', 'rb') as f:
loaded_config = cbor2.load(f)
print(f"\nLoaded: {loaded_config['app_name']} v{loaded_config['version']}")
print(f"Database: {loaded_config['database']['host']}:{loaded_config['database']['port']}")
print(f"MQTT Topics: {', '.join(loaded_config['mqtt']['topics'])}")
# File size comparison
import os
json_size = len(json.dumps(config).encode('utf-8'))
cbor_size = os.path.getsize('config.cbor')
print(f"\nJSON size: {json_size} bytes")
print(f"CBOR size: {cbor_size} bytes")
print(f"Space saved: {json_size - cbor_size} bytes ({(1-cbor_size/json_size)*100:.1f}%)")Go Examples
Example 5: Go CBOR Implementation
Using the fxamacker/cbor library:
Installation:
go get github.com/fxamacker/cbor/v2package main
import (
"fmt"
"log"
"time"
"github.com/fxamacker/cbor/v2"
)
// Define data structure
type SensorReading struct {
DeviceID string `cbor:"device_id"`
Temperature float64 `cbor:"temperature"`
Humidity int `cbor:"humidity"`
Timestamp time.Time `cbor:"timestamp"`
Location Location `cbor:"location"`
Active bool `cbor:"active"`
}
type Location struct {
Building string `cbor:"building"`
Floor int `cbor:"floor"`
Room string `cbor:"room"`
Lat float64 `cbor:"lat"`
Lon float64 `cbor:"lon"`
}
func main() {
// Create sensor reading
reading := SensorReading{
DeviceID: "sensor-go-001",
Temperature: 24.3,
Humidity: 62,
Timestamp: time.Now(),
Location: Location{
Building: "HQ",
Floor: 5,
Room: "Server Room",
Lat: 37.7749,
Lon: -122.4194,
},
Active: true,
}
// Encode to CBOR
cborData, err := cbor.Marshal(reading)
if err != nil {
log.Fatal(err)
}
fmt.Printf("CBOR size: %d bytes\n", len(cborData))
fmt.Printf("CBOR hex: %x\n", cborData)
// Decode from CBOR
var decoded SensorReading
err = cbor.Unmarshal(cborData, &decoded)
if err != nil {
log.Fatal(err)
}
// Verify
fmt.Printf("\nDecoded device: %s\n", decoded.DeviceID)
fmt.Printf("Temperature: %.1f°C\n", decoded.Temperature)
fmt.Printf("Location: %s, Floor %d\n",
decoded.Location.Building, decoded.Location.Floor)
fmt.Printf("Active: %v\n", decoded.Active)
// Data integrity check
if decoded.Temperature == reading.Temperature {
fmt.Println("\nData integrity verified ✓")
}
}Example 6: High-Performance Encoding Options
Optimizing CBOR encoding for production use:
package main
import (
"fmt"
"github.com/fxamacker/cbor/v2"
)
func main() {
// Configure encoding options for optimal performance
encOptions := cbor.EncOptions{
Sort: cbor.SortNone, // Don't sort map keys (faster)
ShortestFloat: cbor.ShortestFloat16, // Use smallest float representation
Time: cbor.TimeUnix, // Encode time as Unix timestamp
}
em, err := encOptions.EncMode()
if err != nil {
panic(err)
}
data := map[string]interface{}{
"sensor_id": "fast-001",
"readings": []float64{23.1, 23.4, 23.7, 24.0},
"timestamp": time.Now(),
"active": true,
}
// Fast encoding with optimized settings
cborData, err := em.Marshal(data)
if err != nil {
panic(err)
}
fmt.Printf("Optimized CBOR: %d bytes\n", len(cborData))
// Decode with matching options
decOptions := cbor.DecOptions{
TimeTag: cbor.DecTagRequired,
}
dm, err := decOptions.DecMode()
if err != nil {
panic(err)
}
var decoded map[string]interface{}
err = dm.Unmarshal(cborData, &decoded)
if err != nil {
panic(err)
}
fmt.Printf("Decoded successfully: %+v\n", decoded)
}Rust Examples
Example 7: Rust CBOR with Serde
Using ciborium for type-safe CBOR encoding:
Cargo.toml dependencies:
[dependencies]
ciborium = "0.2"
serde = { version = "1.0", features = ["derive"] }use serde::{Deserialize, Serialize};
use ciborium::{de::from_reader, ser::into_writer};
use std::io::Cursor;
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct TelemetryData {
device_id: String,
temperature: f64,
pressure: f64,
humidity: u8,
timestamp: u64,
location: GpsCoordinates,
alerts: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct GpsCoordinates {
latitude: f64,
longitude: f64,
altitude: f64,
}
fn main() {
// Create telemetry data
let telemetry = TelemetryData {
device_id: "rust-sensor-01".to_string(),
temperature: 25.3,
pressure: 1013.25,
humidity: 65,
timestamp: 1703422800,
location: GpsCoordinates {
latitude: 37.7749,
longitude: -122.4194,
altitude: 52.0,
},
alerts: vec!["temperature_high".to_string()],
};
// Encode to CBOR
let mut cbor_buffer = Vec::new();
into_writer(&telemetry, &mut cbor_buffer)
.expect("Failed to encode CBOR");
println!("CBOR size: {} bytes", cbor_buffer.len());
println!("CBOR hex: {}", hex::encode(&cbor_buffer));
// Decode from CBOR
let cursor = Cursor::new(&cbor_buffer);
let decoded: TelemetryData = from_reader(cursor)
.expect("Failed to decode CBOR");
println!("\nDecoded device: {}", decoded.device_id);
println!("Temperature: {}°C", decoded.temperature);
println!("Location: {}, {}",
decoded.location.latitude,
decoded.location.longitude);
// Verify data integrity
assert_eq!(telemetry, decoded);
println!("\nData integrity verified ✓");
}Java Example
Example 8: Java CBOR with Jackson
Using Jackson's CBOR data format module:
Maven dependency:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-cbor</artifactId>
<version>2.16.0</version>
</dependency>import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import java.util.*;
public class CborExample {
static class DeviceData {
public String deviceId;
public double temperature;
public int humidity;
public long timestamp;
public Map<String, Object> metadata;
public List<Double> readings;
// Constructors, getters, setters...
}
public static void main(String[] args) throws Exception {
// Create ObjectMapper with CBOR factory
ObjectMapper mapper = new ObjectMapper(new CBORFactory());
// Create device data
DeviceData device = new DeviceData();
device.deviceId = "java-sensor-001";
device.temperature = 23.8;
device.humidity = 58;
device.timestamp = System.currentTimeMillis();
device.metadata = new HashMap<>();
device.metadata.put("location", "Building B");
device.metadata.put("floor", 2);
device.metadata.put("zone", "North Wing");
device.readings = Arrays.asList(22.1, 23.0, 23.8, 24.2);
// Encode to CBOR
byte[] cborBytes = mapper.writeValueAsBytes(device);
System.out.println("CBOR size: " + cborBytes.length + " bytes");
// Decode from CBOR
DeviceData decoded = mapper.readValue(cborBytes, DeviceData.class);
// Verify
System.out.println("\nDecoded device: " + decoded.deviceId);
System.out.println("Temperature: " + decoded.temperature + "°C");
System.out.println("Location: " + decoded.metadata.get("location"));
System.out.println("Readings: " + decoded.readings);
// Data integrity check
assert device.deviceId.equals(decoded.deviceId);
assert device.temperature == decoded.temperature;
System.out.println("\nData integrity verified ✓");
}
}Real-World Integration Examples
Example 9: MQTT + CBOR for IoT
Combining MQTT messaging with CBOR encoding for efficient IoT data transmission:
const mqtt = require('mqtt');
const { encode, decode } = require('cbor-x');
// Connect to MQTT broker
const client = mqtt.connect('mqtt://broker.example.com', {
clientId: 'sensor-node-' + Math.random().toString(16).substr(2, 8),
clean: true,
reconnectPeriod: 1000
});
client.on('connect', () => {
console.log('Connected to MQTT broker');
// Subscribe to commands
client.subscribe('devices/sensor-001/commands', (err) => {
if (!err) console.log('Subscribed to commands');
});
});
// Publish sensor data with CBOR encoding
function publishSensorData() {
const sensorData = {
deviceId: 'sensor-001',
timestamp: Date.now(),
temperature: 20 + Math.random() * 10,
humidity: 40 + Math.random() * 40,
pressure: 1010 + Math.random() * 10,
battery: 85 + Math.random() * 15
};
// Encode to CBOR (smaller payload = lower bandwidth)
const cborPayload = encode(sensorData);
client.publish('devices/sensor-001/data', cborPayload, {
qos: 1,
retain: false
}, (err) => {
if (!err) {
console.log(`Published ${cborPayload.length} bytes (CBOR)`);
// JSON would be ~150 bytes, CBOR is ~95 bytes (37% savings)
}
});
}
// Receive and decode commands
client.on('message', (topic, message) => {
if (topic === 'devices/sensor-001/commands') {
try {
const command = decode(message);
console.log('Received command:', command);
// Process command
if (command.action === 'configure') {
console.log('Updating configuration:', command.settings);
}
} catch (err) {
console.error('Failed to decode command:', err);
}
}
});
// Send data every 30 seconds
setInterval(publishSensorData, 30000);Bandwidth savings: CBOR reduces MQTT payload size by 30-50%, lowering data costs and enabling longer battery life for IoT devices.
Example 10: HTTP API with CBOR Support
Express.js API endpoint supporting both JSON and CBOR:
const express = require('express');
const { encode, decode } = require('cbor-x');
const app = express();
// Middleware to handle CBOR requests
app.use((req, res, next) => {
if (req.get('Content-Type') === 'application/cbor') {
let data = [];
req.on('data', chunk => data.push(chunk));
req.on('end', () => {
try {
req.body = decode(Buffer.concat(data));
next();
} catch (err) {
res.status(400).send('Invalid CBOR');
}
});
} else {
express.json()(req, res, next);
}
});
// API endpoint supporting both formats
app.post('/api/sensors/data', (req, res) => {
console.log('Received sensor data:', req.body);
const response = {
success: true,
deviceId: req.body.deviceId,
receivedAt: new Date().toISOString(),
dataPoints: req.body.readings?.length || 0
};
// Respond with same format as request
const acceptCbor = req.get('Accept')?.includes('application/cbor');
if (acceptCbor) {
res.set('Content-Type', 'application/cbor');
res.send(encode(response));
} else {
res.json(response);
}
});
// Client example
const axios = require('axios');
async function sendSensorData() {
const data = {
deviceId: 'sensor-042',
readings: [23.1, 23.4, 23.7],
timestamp: Date.now()
};
// Send as CBOR
const response = await axios.post(
'http://localhost:3000/api/sensors/data',
encode(data),
{
headers: {
'Content-Type': 'application/cbor',
'Accept': 'application/cbor'
},
responseType: 'arraybuffer'
}
);
const result = decode(Buffer.from(response.data));
console.log('Server response:', result);
}
app.listen(3000, () => {
console.log('API server with CBOR support running on port 3000');
});Best Practices
Error Handling
Always wrap CBOR encoding/decoding in try-catch blocks. Malformed binary data can cause parsing errors. Validate data structure before encoding and after decoding for production applications.
Version Compatibility
Include version information in your CBOR payloads when schema changes are expected. Tag values (CBOR tags 0-255) can be used to indicate data format versions for backward compatibility.
Performance Optimization
For high-throughput applications, reuse encoder/decoder instances rather than creating new ones for each operation. Most CBOR libraries support instance pooling or singleton patterns for better performance.
Binary Data
Use CBOR's native binary type for images, encrypted data, and other binary content. This avoids base64 encoding overhead and reduces payload size by approximately 33% compared to JSON with base64.
Content Negotiation
For HTTP APIs, support both JSON and CBOR using Content-Type and Accept headers (application/cbor). This allows clients to choose the format that best suits their needs while maintaining backward compatibility.
CBOR Development Tools
Test and validate CBOR data using these online tools:
Additional Resources
- •RFC 8949: CBOR Specification - Official IETF standard for CBOR data format
- •CBOR.io - Official CBOR website with implementations in all languages
- •cbor-x on NPM - High-performance JavaScript CBOR library (2M+ weekly downloads)
- •cbor2 on PyPI - Pure Python CBOR implementation
- •fxamacker/cbor - Production-ready Go CBOR library with security focus
- •Ciborium (Rust) - Serde-based CBOR codec for Rust
- •CBOR GitHub Organization - Official repositories and reference implementations
- •W3C WebAuthn Specification - Web authentication standard using CBOR for credentials
- •RFC 8152: COSE - CBOR Object Signing and Encryption standard
- •What is CBOR? - Introduction to CBOR format and benefits
- •CBOR vs JSON - Detailed format comparison with benchmarks