CBOR(RFC 8949)是 IETF 定义的二进制数据格式。本转换器使用标准映射而非特定库的记录扩展,并通过 JSON 包装器往返处理字节串、大整数、浮点数、数组、非字符串键映射、日期、undefined 值和语义标签。
当通信双方需要 JSON 不具备的类型时可使用 CBOR,但必须约定语义标签的解释方式和确定性编码配置。本转换器不保证生成规范化字节;编辑 JSON 时须保留 $binary、$map、$cborTag、$date、$undefined 和整数包装器。
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