UBJSON 转 JSON 转换器

UBJSON 转 JSON

关于 UBJSON

什么是 UBJSON?

UBJSON 是一种使用标记表示 JSON 值的二进制编码。本转换器可解码 null 和布尔值、整数与浮点类型、高精度数、字符和字符串、数组、对象、no-op 标记、类型化或计数容器以及优化的 uint8 数组;编码时还接受表示二进制、int64、float64 和高精度值的 JSON 包装器。

什么时候使用 UBJSON?

UBJSON 主要用于兼容现有集成。请确认对端支持以 $ 表示的类型化容器、以 # 表示的计数容器以及高精度 H 标记;本转换器会生成计数容器和优化的 uint8 数组,并拒绝不支持的标记或尾随字节。

JavaScript 中的 UBJSON

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);
});
			

Go 中的 UBJSON

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 中的 UBJSON

<?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