MessagePack 转 JSON 转换器

MessagePack 转 JSON

关于 MessagePack

什么是 MessagePack?

MessagePack 是一种紧凑的二进制序列化格式。本转换器可通过显式 JSON 包装器处理 null、布尔值、字符串、数字、数组、字符串键映射、二进制数据、时间戳、有符号和无符号 64 位整数以及扩展值。

什么时候使用 MessagePack?

仅在两端采用兼容的 MessagePack 实现,并约定时间戳和扩展类型代码含义时使用。通过 JSON 传递值时必须保留 $binary、$numberLong、$uint64、$date 和 $messagePackExt 包装器,否则会丢失类型信息。

JavaScript 中的 MessagePack

import { encode, decode } from '@msgpack/msgpack';

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: 81a568656c6c6fa5776f726c64

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

Go 中的 MessagePack

package main

import (
	"fmt"

	"github.com/vmihailenco/msgpack/v5"
)

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

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

PHP 中的 MessagePack

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

use MessagePack\MessagePack;

$value = ['hello' => 'world'];
$encoded = MessagePack::pack($value);
echo bin2hex($encoded) . PHP_EOL;
// Output: 81a568656c6c6fa5776f726c64

$decoded = MessagePack::unpack($encoded);
echo $decoded['hello'] . PHP_EOL;
// Output: world