@genrojs/tytx

中文文档
0.16.4发布于 2026/10/25Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 4284

在JSON,XML和MessagePack上打入了Python和JavaScript之间的数据交换:十进制,日期和自定义类型随其类型而来.

中文使用文档
文档目录16 节
  1. 你知道的痛苦
  2. TYTX 解决方案
  3. 30-二级民主
  4. 未键入的 JSON 编码器
  5. 记录流(JSON线)
  6. 自定义类型
  7. 安装
  8. 真实世界实例:秩序处理
  9. 1. 数据
  10. 2. 没有TYTX:20个人工转换
  11. 3. 与TYTX:零转换
  12. 奖励: 切换到一行中的信件包
  13. 支持类型
  14. 何时使用 TYTX
  15. 文档
  16. 许可证

TYTX Logo

PyPI JSR Python 3.10+ License Status
Tests Coverage Documentation

常规- tytx

轻量级多运量型数据交换系统.

TYTX取消了Python和JavaScript之间的手动类型转换,并让切换到MessagePack,以便像改变一个参数那样简单地实现更好的性能.

你送一个 Decimal 从Python, JavaScript 接收到一个字符串. 你把它转换回来。 每一个 单身. 时间 TYTX 在 Python 和 JavaScript 之间自动修正此类型, 超过 JSON, XML, 或 MessagePack .

你知道的痛苦

# Your Python API
return {"price": Decimal("99.99"), "due_date": date(2025, 1, 15)}
// Your JavaScript client
const data = await response.json();
// data.price is "99.99" (string) - need to convert
// data.due_date is "2025-01-15" (string) - need to convert

const price = new Decimal(data.price);      // Manual conversion
const dueDate = new Date(data.due_date);    // Manual conversion

这导致:

  • 转换代码分散于各地
  • 当有人忘记皈依时会出现虫子
  • 有浮动点错误的财务计算
  • 不同日期格式导致一天出错

TYTX 解决方案

# Server - just return native types
return {"price": Decimal("99.99"), "due_date": date(2025, 1, 15)}
// Client - types arrive ready to use
const data = await fetchTytx('/api/order');
data.price      // → Decimal (not string)
data.due_date   // → Date (not string)

零转换码. 类型只是工作.

30-二级民主

Python : (中文(简体) )

pip install genro-tytx
from decimal import Decimal
from datetime import date
from genro_tytx import to_tytx, from_tytx

# Encode
data = {"price": Decimal("99.99"), "date": date(2025, 1, 15)}
encoded = to_tytx(data)
# '{"price":"99.99::N","date":"2025-01-15::D"}::JS'

# Decode
decoded = from_tytx(encoded)
# {"price": Decimal("99.99"), "date": date(2025, 1, 15)}

Java 脚本 :

npm install @genrojs/tytx   # npm
bunx jsr add @genro/tytx    # JSR
import { fetchTytx } from '@genro/tytx';
import Big from 'big.js';

const result = await fetchTytx('/api/invoice', {
    body: { price: new Big('99.99'), date: new Date() }
});
// result.total → Big (ready to use)

未键入的 JSON 编码器

除了键入 to_tytx 编号 : from_tytx API, TYTX 曝光了用于未打字路径的平面 JSON 编码器——没有类型后缀,只是快了 JSON (orjson 当可用时, stdlib 否则):

from genro_tytx import json_dumps, json_loads

json_dumps({"a": 1})        # -> b'{"a":1}'   (UTF-8 bytes)
json_loads('{"a": 1}')      # accepts str or bytes -> {"a": 1}

json_dumps 返回 UTF-8 bytes (准备ASGI/WebSocket发送), json_loads 接受 str 或者说 bytes。当您想要普通 JSON 时使用这些;使用 to_tytx 编号 : from_tytx 当您想要输入的数值流出时.

记录流(JSON线)

to_tytx_iter 编号 : from_tytx_iter (贾瓦脚本) toTytxIter 编号 : fromTytxIter)取一取一取一取一取一取一取一取一取一取一取一取还一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取 编码将输入的值转换为 "value::CODE" 无字符串 ::JS 每个记录都是普通的JSON,一个JSONL线. 解码使这些字符串重新变成被打入的值,并让其他一切保持不变. 同步源给出了活化器,活化源给出了活化器. 分流为行属于JSONL阅读器或编剧.

from genro_tytx import to_tytx_iter, from_tytx_iter

for record in to_tytx_iter(rows):                  # rows: dicts with Decimal, date, ...
    out.write(json.dumps(record) + "\n")           # {"price": "12.50::N", "day": "2026-10-22::D"}

for record in from_tytx_iter(json.loads(line) for line in open("orders.jsonl")):
    ...                                            # record["price"] is a Decimal

async for record in from_tytx_iter(async_records): # async source -> async iterator
    ...

通过 HTTP 传输流为 Content-Type: application/jsonl 与 X-TYTX-Transport: jsonl· ; getTransport 返回时 'jsonl' 对于它。 结束早期的回复看起来像一个完整的回复:在信头后报告错误,或预期的记录数量取决于应用程序.

自定义类型

register_type 让外部包教 TYTX 一种新类型——在自定义后缀下串行化钩(object → string)和去区域化钩(string → object). 软件包在自己的导入时间注册,因此TYTX不会因此而获得依赖:

from genro_tytx import register_type, to_tytx, from_tytx

class Point:
    def __init__(self, x, y): self.x, self.y = x, y

register_type(Point, "PT", lambda p: f"{p.x},{p.y}",
              lambda s: Point(*map(int, s.split(","))))

to_tytx([1, Point(5, 6), "k"])   # '[1,"5,6::PT","k"]::JS'
from_tytx('5,6::PT')             # Point(5, 6)

自定义类型会像任何内置的scalar一样流出,包括嵌入于dicts和列表中. 具体类型首先匹配;一个未注册的已注册类型子类按照该类型代码旅行,由它自己的序列器(genro-builders')编写 SourceBag 作为天才包子旅行 X),内置类型保持了精确类型规则. 一个阶级不能以另一个阶级拥有的代码注册. 一个代码是一个或多个大写 ASCII 字母,任意长度;注册拒绝其他任何内容. 重新登记同一类会取代其钩;重用由不同类型拥有的后缀会引起错误. 接收方的未知代码并非出错:字符串返回时未受影响. 同样的语义适用于JavaScript客户端(registerType 编号 : registerClass) (中文(简体) ). 消费者保留的规则和代码载于 spec/TYTX-SPEC.md 第2.5节.

当类型拥有它的序列化, register_class 读取来自类本身的钩子——可以用作装饰. 这需要 __tytx_suffix__,一个实例 to_tytx() (单位:千美元) from_tytx 类方法( c)from_tytx 必须是类方法: 解码从后缀开始, 从头重建实例 :

from genro_tytx import register_class

@register_class
class Point:
    __tytx_suffix__ = "PT"
    def __init__(self, x, y): self.x, self.y = x, y
    def to_tytx(self): return f"{self.x},{self.y}"
    @classmethod
    def from_tytx(cls, s): return cls(*map(int, s.split(",")))

子类的混凝土类是该类型自己的业务. TYTX每个代码保存一个子类型词典,从未读取过: set_subtype_dict(suffix, dict) 替换它, get_subtype_dict(suffix) 返回( r){} 如果没有设定的话)。 Java 脚本 : setSubtypeDict 编号 : getSubtypeDict类型 to_tytx编号 :from_tytx 使用它; 添加子类调用者 register_subtype(suffix, cls, name=None) (贾瓦脚本) registerSubtype),它以自己的名称添加该类,或者在以下 name,如果名称已经属于另一类,则提出。 Genro -bag 地图符号名称的 Bag 类这种方式.

安装

# Python
pip install genro-tytx

# JavaScript/TypeScript, from npm
npm install @genrojs/tytx

# JavaScript/TypeScript, from JSR
bunx jsr add @genro/tytx
# With npm: npx jsr add @genro/tytx

JavaScript包括"十进制","大","MessagePack"和"XML"的依赖性. 无单独的 需要安装代码 。 Python额外项目保持不变.

真实世界实例:秩序处理

典型的业务情景:处理一个有8个打字字字的订单,返回6个打字结果.

1. 数据

JavaScript 客户端 有带有适当类型的命令数据 :

import Big from 'big.js';

const orderData = {
    unit_price: new Big('149.99'),      // Decimal
    quantity: 3,
    discount: new Big('10.00'),         // Decimal
    order_date: new Date(2025, 0, 15),  // Date
    delivery_date: new Date(2025, 0, 20),
    express: true,
    customer_id: 12345,
    notes: 'Handle with care'
};

// Expects response: { subtotal, tax, shipping, total, ship_date, arrival_date }

Python 服务器 有商业逻辑期待合适的类型 :

async def process_order(unit_price, quantity, discount, order_date,
                        delivery_date, express, customer_id, notes):
    """Business logic - expects Decimal and date types."""
    subtotal = unit_price * quantity
    tax = subtotal * Decimal('0.22')
    shipping = Decimal('15.00') if express else Decimal('5.00')
    total = subtotal - discount + tax + shipping
    ship_date = order_date + timedelta(days=1 if express else 3)
    return {
        'subtotal': subtotal, 'tax': tax, 'shipping': shipping,
        'total': total, 'ship_date': ship_date, 'arrival_date': delivery_date
    }

2. 没有TYTX:20个人工转换

Java 脚本 - 必须转换为/从字符串:

// Send: convert types → strings
const response = await fetch('/api/process_order', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        unit_price: orderData.unit_price.toString(),           // Decimal → string
        discount: orderData.discount.toString(),               // Decimal → string
        order_date: orderData.order_date.toISOString().slice(0, 10),  // Date → string
        delivery_date: orderData.delivery_date.toISOString().slice(0, 10),
        quantity: orderData.quantity, express: orderData.express,
        customer_id: orderData.customer_id, notes: orderData.notes
    })
});

// Receive: convert strings → types
const json = await response.json();
const result = {
    subtotal: new Big(json.subtotal),     tax: new Big(json.tax),
    shipping: new Big(json.shipping),     total: new Big(json.total),
    ship_date: new Date(json.ship_date),  arrival_date: new Date(json.arrival_date)
};

蟒 - 必须转换为/从字符串:

@app.post("/api/process_order")
async def handle_order(request: Request):
    json_data = await request.json()

    # Receive: convert strings → types
    unit_price = Decimal(json_data['unit_price'])
    discount = Decimal(json_data['discount'])
    order_date = date.fromisoformat(json_data['order_date'])
    delivery_date = date.fromisoformat(json_data['delivery_date'])

    result = await process_order(unit_price, json_data['quantity'], discount,
        order_date, delivery_date, json_data['express'],
        json_data['customer_id'], json_data['notes'])

    # Send: convert types → strings
    return JSONResponse({
        'subtotal': str(result['subtotal']), 'tax': str(result['tax']),
        'shipping': str(result['shipping']), 'total': str(result['total']),
        'ship_date': result['ship_date'].isoformat(),
        'arrival_date': result['arrival_date'].isoformat()
    })

共计:20个人工改划 (4个JS=字符串+4个字符串+Python+6个Python+字符串+6个字符串+JS).


3. 与TYTX:零转换

import { fetchTytx } from '@genro/tytx';

const result = await fetchTytx('/api/process_order', { body: orderData });
console.log(result.total.toFixed(2));  // Big, ready to use

共计:0个改划。 类型自然地流动.

奖励: 切换到一行中的信件包

要更好的性能需要二进制格式吗 ? 刚刚添加 transport: 'msgpack'数字 :

// JSON (default)
const result = await fetchTytx('/api/process_order', { body: orderData });

// MessagePack - same API, binary format
const result = await fetchTytx('/api/process_order', { body: orderData, transport: 'msgpack' });

支持类型

蟒Java 脚本线条格式
DecimalDecimal (大号.js)"99.99::N"
dateDate (协调世界时午夜)"2025-01-15::D"
datetimeDate"2025-01-15T10:30:00.000Z::DHZ"
timeDate (时代日期)"10:30:00.000::H"
bytesUint8Array"AAEC::RAW" (base64;MessagePack上的本地文件夹)

原生JSON类型(字符串,数字,布尔,无效)经过不变.

何时使用 TYTX

不错:

  • 含有日期/ 十进制格式的 Web 应用程序
  • 需要小数精确度的财务应用
  • 经常发送/接收输入数据的API
  • 混合类型类似 Excel 的网格

无需:

  • 仅使用字符串和整数的 API
  • 没有特殊类型的简单 CRUD
  • 已使用全类型支持的 GraphQL/Protobuf

文档

我想... 说说看 I want to...继续...
五分钟内试试看快速启动
用在 HTTP 上HTTP 整合
理解线条格式如何运作
见 API 参考API 参考
与替代品相比替代品

许可证

Apache许可证2.0 - 版权2025 Softwell S.r.l.

版本与发布记录

@genrojs/tytx 共发布 4 个版本,首次发布于 2026/10/01;过去 12 个月发布了 4 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.16.4latest2026/10/2522 天前
0.16.32026/10/1927 天前
0.16.22026/10/041 个月前
0.16.12026/10/011 个月前

关于 @genrojs/tytx 的常见问题

@genrojs/tytx 是什么?

在JSON,XML和MessagePack上打入了Python和JavaScript之间的数据交换:十进制,日期和自定义类型随其类型而来.

如何安装 @genrojs/tytx?

在项目目录运行 npm install @genrojs/tytx,或使用 pnpm add / yarn add / bun add。

@genrojs/tytx 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@genrojs/tytx 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@genrojs/tytx 可以商用吗?

@genrojs/tytx 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@genrojs/tytx 的下载量有多少?

根据 npm 官方下载统计,@genrojs/tytx 在 2026/10/16 – 2026/11/14 这 30 天内被下载 4,284 次,日均约 143 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@genrojs/tytx 还在维护吗?

最新版本 0.16.4 发布于 2026/10/25(22 天前);至今共发布 4 个版本,其中过去 12 个月发布了 4 个;首次发布于 2026/10/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。