CBOR 是 IETF 定义的紧凑二进制序列化格式,适用于 JSON 形态和带类型的数据,支持字节串、标签、数组、键值映射以及超出普通 JSON 限制的整数。
当协议载荷、嵌入式系统、签名或封装数据需要字节串、语义标签、非字符串键,或需要确定性的二进制序列化时,可以使用 CBOR。
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' }
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
}
<?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