MessagePack 是一种紧凑的二进制序列化格式,用于 JSON 形态的数据,支持字符串、数字、数组、键值映射、二进制数据、时间戳和扩展值。
当接口载荷、缓存项、队列消息或日志需要比 JSON 更小的二进制表示,并且两端都支持 MessagePack 时,可以使用 MessagePack,同时保留接近 JSON 的数据模型。
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' }
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
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