Universal Binary JSON 是用于 JSON 值的二进制序列化格式,支持类型化数字、字符串、数组、对象、二进制字节数组和优化的类型化容器。
当需要兼容已经输出 Universal Binary JSON 的系统,尤其是数值数组或带类型的二进制数据时,可以使用 UBJSON。新协议则建议同时比较 MessagePack 和 CBOR 的库支持。
const UBJSON = require('ubjson');
// The npm package is legacy; use it mainly for compatibility with existing UBJSON data.
const value = { hello: 'world' };
const buffer = Buffer.alloc(1024);
const offset = UBJSON.packToBufferSync(value, buffer);
const encoded = buffer.subarray(0, offset);
console.log(encoded.toString('hex'));
UBJSON.unpackBuffer(encoded, (error, decoded) => {
if (error) throw error;
console.log(decoded);
});
package main
import (
"fmt"
"github.com/jmank88/ubjson"
)
func main() {
value := map[string]any{"hello": "world"}
encoded, _ := ubjson.Marshal(value)
fmt.Printf("%x\n", encoded)
var decoded map[string]any
_ = ubjson.Unmarshal(encoded, &decoded)
fmt.Println(decoded["hello"])
// Output: world
}
<?php
// PHP does not have a widely used maintained UBJSON package.
// This writes the common optimized uint8 array form used for binary payloads.
$bytes = "\x01\x02\x03";
$encoded = '[' . '$' . 'U' . '#' . 'U' . chr(strlen($bytes)) . $bytes;
echo bin2hex($encoded) . PHP_EOL;
// Output: 5b2455235503010203