CBOR to JSON

About CBOR

What is CBOR?

CBOR is a compact IETF binary serialization format for JSON-shaped and typed data. It supports byte strings, tags, arrays, key-value maps, and integers beyond normal JSON limits.

When to use CBOR?

Use CBOR for protocol payloads, embedded systems, signed or enveloped data, and formats that need byte strings, semantic tags, non-string map keys, or deterministic binary serialization.

CBOR in JavaScript

import { encode, decode } from 'cbor-x';

const value = { hello: 'world' };
const bytes = encode(value);
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');

console.log(hex);
// Output: a16568656c6c6f65776f726c64

console.log(decode(bytes));
// Output: { hello: 'world' }
				

CBOR in Go

package main

import (
	"fmt"

	"github.com/fxamacker/cbor/v2"
)

func main() {
	value := map[string]any{"hello": "world"}
	encoded, _ := cbor.Marshal(value)
	fmt.Printf("%x\n", encoded)
	// Output: a16568656c6c6f65776f726c64

	var decoded map[string]any
	_ = cbor.Unmarshal(encoded, &decoded)
	fmt.Println(decoded["hello"])
	// Output: world
}
				

CBOR in PHP

<?php
require 'vendor/autoload.php';

use CBOR\Decoder;
use CBOR\MapObject;
use CBOR\StringStream;
use CBOR\TextStringObject;

$value = MapObject::create()
	->add(TextStringObject::create('hello'), TextStringObject::create('world'));

$encoded = (string) $value;
echo bin2hex($encoded) . PHP_EOL;
// Output: a16568656c6c6f65776f726c64

$decoded = Decoder::create()->decode(StringStream::create($encoded))->normalize();
echo $decoded['hello'] . PHP_EOL;
// Output: world