JSON压缩工具

JSON2TOON是一个高级JSON压缩系统,通过AI驱动的模式检测实现75-85%的令牌减少,同时保持完美数据完整性。

  • by muhammedehab35
  • Python
  • 本地部署
  • 9 星标
  • 更新于
在 GitHub 查看 muhammedehab35/JSON2TOON-MCP

使用说明

JSON2TOON v2.0🚀

高级令牌优化对象表示法 -用于AI上下文管理的最强大的JSON压缩系统。

JSON2TOON是下一代MCP服务器,它通过AI驱动的模式检测彻底改变了JSON压缩,实现了 代币减少75-85% 同时保持完美的数据完整性。


✨ 主要特点

🎯 4个压缩级别

  • 最小 (节省30-40%):闪电般快速的按键缩写
  • 标准 (节省40-60%):平衡的性能+压缩
  • 激进的 (节省60-75%):高级模式优化
  • 极端 (节省75-85%):使用zlib实现最大压缩

🤖 AI驱动的模式检测

  • 17+图案类型:API响应、数据库、时间序列、图形、树等
  • 智能策略选择:基于数据结构的自动优化
  • 信心评分:每种模式都有准确度指标
  • 压缩潜力:估计转换前的节省额

🔧 12个高级MCP工具

  1. convert_to_toon -多级JSON压缩
  2. convert_to_json -无损减压
  3. analyze_patterns -基于AI的深度模式分析
  4. get_optimal_strategy -AI推荐的压缩方案
  5. calculate_metrics -详细的压缩统计数据
  6. batch_convert -高性能批处理
  7. smart_optimize -自动检测并应用最佳压缩
  8. compare_levels -并排水平比较
  9. validate_toon -格式验证+往返测试
  10. suggest_abbreviations -自定义缩写生成
  11. estimate_savings -转换前节省估算
  12. get_server_stats -实时性能指标

💡 高级能力

  • 150+关键缩写 (与TOON v1.0中的68相比)
  • 字符串字典:重复值的重复数据消除
  • 部分架构压缩:处理不一致的数据
  • 值模式压缩:优化时间戳、UUID、URL和电子邮件
  • 参考系统:消除重复结构
  • zlib集成:可选极端压缩

📊 性能基准

数据类型 压缩 速度 往返
API响应 50-65% 0.3毫秒/KB ✅ 太好了!
数据库结果 60-70% 0.3毫秒/KB ✅ 太好了!
时间序列 65-75% 0.5ms/KB ✅ 太好了!
用户档案 45-55% 0.3毫秒/千字节 ✅ 太好了!
配置文件 40-55% 0.1ms/KB ✅ 太好了!

🚀 快速开始

安装

# Clone repository
git clone https://github.com/muhammedehab35/JSON2TOON-MCP.git
cd json2toon

# Install with pip
pip install -e .

# Or use Docker
docker-compose up -d

MCP配置

添加到您的Claude桌面配置(~/.config/Claude/claude_desktop_config.json):

{
  "mcpServers": {
    "json2toon": {
      "command": "python",
      "args": ["-m", "src.mcp_server"],
      "cwd": "/path/to/json2toon"
    }
  }
}

Docker配置:

{
  "mcpServers": {
    "json2toon": {
      "command": "docker",
      "args": ["run", "-i", "json2toon:2.0.0"]
    }
  }
}

💻 使用示例

基本转换

from src.advanced_converter import convert_json_to_toon, convert_toon_to_json, CompressionLevel

# Simple conversion with STANDARD level
data = {
    "id": 12345,
    "name": "John Doe",
    "email": "john@example.com",
    "created_at": "2025-01-01T00:00:00Z"
}

# Convert to TOON
toon = convert_json_to_toon(data, level=CompressionLevel.STANDARD)
print(f"Compressed: {toon}")

# Convert back to JSON
original = convert_toon_to_json(toon)
print(f"Restored: {original}")

高级模式分析

from src.pattern_analyzer import AdvancedPatternAnalyzer

analyzer = AdvancedPatternAnalyzer()

# Analyze your data
patterns = analyzer.analyze(large_json_data)

# Get compression strategy
strategy = analyzer.get_compression_strategy(large_json_data)

print(f"Detected {len(patterns)} patterns")
print(f"Expected savings: {strategy.expected_savings * 100:.1f}%")
print(f"Recommended level: {strategy.recommended_level}")
print(f"Reasoning: {strategy.reasoning}")

智能优化

from src.optimizer import SmartOptimizer

optimizer = SmartOptimizer()

# Automatic optimization with profile
result = optimizer.optimize(data, profile="balanced")
# Profiles: "speed", "balanced", "size"

print(f"Used profile: {result['profile_used']}")
print(f"Selected level: {result['level_selected']}")
print(f"Savings: {result['metrics']['savings_percent']:.1f}%")

批处理

from src.advanced_converter import AdvancedTOONConverter, CompressionLevel

converter = AdvancedTOONConverter(level=CompressionLevel.AGGRESSIVE)

# Process multiple items
items = [
    {"id": i, "data": f"Item {i}"}
    for i in range(1000)
]

for item in items:
    toon = converter.json_to_toon(item)
    # Process compressed data

🔬 MCP工具示例

克劳德密码

1.转换为自定义级别

Use the convert_to_toon tool with:
- json_data: <your JSON>
- level: 3 (AGGRESSIVE)

2.分析模式

Use the analyze_patterns tool to detect:
- Pattern types
- Compression potential
- Optimization recommendations

3.比较所有级别

Use the compare_levels tool to see:
- Side-by-side comparison
- Savings per level
- Best recommendation

4.智能自动优化

Use the smart_optimize tool with:
- json_data: <your JSON>
- profile: "size" (for maximum compression)

📖 格式规范

TOON v2.0结构

{
  "_toon": "2.0",           // Version identifier
  "_lvl": 2,                // Compression level used
  "d": {...},               // Compressed data
  "_refs": {...},           // Optional: structure references
  "_dict": {...}            // Optional: string dictionary
}

关键缩写(示例)

原件 TOON 原件 TOON 原件 TOKON
ID I 电子邮件 EML 状态 s
姓名 n 电话 ph created_at ca
类型 t 地址 addr updated_at ua
value v 用户名 unm 时间戳 ts

150+缩写 涵盖常见的API、数据库和应用程序领域。

价值优化

  • null → ~
  • true → T, false → F
  • 时间戳: $ts:2025-01-01T00:00:00Z
  • UUID: $uid:550e8400-e29b-41d4-a716-446655440000
  • 字符串引用: @s0, @s1 (摘自词典)

架构压缩

之前:

[
  {"id": 1, "name": "Alice", "email": "alice@test.com"},
  {"id": 2, "name": "Bob", "email": "bob@test.com"},
  {"id": 3, "name": "Carol", "email": "carol@test.com"}
]

之后(TOON):

{
  "_sch": ["i", "n", "eml"],
  "_dat": [
    [1, "Alice", "alice@test.com"],
    [2, "Bob", "bob@test.com"],
    [3, "Carol", "carol@test.com"]
  ]
}

储蓄:对于具有一致模式的数组,约55-60%


🧪 测试

# Run all tests
pytest tests/ -v

# With coverage
pytest tests/ --cov=src --cov-report=html

# Specific test file
pytest tests/test_converter.py -v

# Run tests in Docker
docker-compose run json2toon-server pytest tests/ -v

测试覆盖率

  • ✅ 转换器:100多个测试用例,涵盖所有压缩级别
  • ✅ 模式分析器:对所有17种图案类型进行30多次测试
  • ✅ 往返:完美的数据完整性验证
  • ✅ 边缘案例:Unicode、大数字、特殊字符
  • ✅ 演出:各级基准

🐳 Docker部署

塑造形象

docker build -t json2toon:2.0.0 .

使用Docker Compose运行

# Production mode
docker-compose up -d json2toon-server

# Development mode
docker-compose --profile dev up json2toon-dev

Docker功能

  • ✅ Python 3.11优化镜像
  • ✅ 非root用户安全
  • ✅ 健康检查
  • ✅ 资源限制(2个CPU,1GB RAM)
  • ✅ 日志配置
  • ✅ 实时重装开发模式

📐 建筑

┌─────────────────────────────────────────┐
│         JSON2TOON MCP Server            │
│              (v2.0)                     │
└─────────────┬───────────────────────────┘
              │
    ┌─────────┼─────────┐
    │         │         │
    ▼         ▼         ▼
┌─────────┐ ┌──────────┐ ┌──────────┐
│Advanced │ │Pattern   │ │Smart     │
│Converter│ │Analyzer  │ │Optimizer │
└─────────┘ └──────────┘ └──────────┘
    │         │              │
    └─────────┴──────────────┘
              │
    ┌─────────┼─────────┐
    ▼         ▼         ▼
┌──────┐  ┌──────┐  ┌──────┐
│Schema│  │String│  │Value │
│Comp  │  │ Dict │  │ Comp │
└──────┘  └──────┘  └──────┘

🎯 检测到的图案类型

  1. API响应 -REST、GraphQL、JSON-RPC
  2. 数据库记录 -CRUD、审计日志、版本控制
  3. 用户数据 -配置文件、身份验证、首选项
  4. 分页 -基于页面、基于偏移量
  5. 嵌套地址 -街道、城市、州、国家
  6. 嵌套坐标 -拉丁语/液化天然气/替代语
  7. 嵌套尺寸 -宽度/高度/深度
  8. 嵌套元数据 -由标签创建/更新
  9. 同构数组 -同类型元素
  10. 一致架构数组 -相似的对象结构
  11. 重复结构 -重复图案
  12. 时间序列 -时间数据序列
  13. 图节点 -网络/图形结构
  14. 树形结构 -分层数据
  15. 枚举值 -有限值集
  16. 稀疏数组 -许多空值
  17. 深巢 -复杂嵌套级别

🔧 发展

设置开发环境

# Install dev dependencies
pip install -e ".[dev]"

# Format code
black src/ tests/

# Lint
ruff src/ tests/

# Type check
mypy src/

代码质量工具

  • 黑色:代码格式(行长:100)
  • 颈毛:快速Python linter
  • 米皮:静态类型检查(严格模式)
  • pytest:支持异步的测试框架

📊 与TOON v1.0的比较

功能 TOON v1.0 JSON2TOON v2.0
压缩级别 2 4
关键缩写 68 150+
图案类型 8 17+
MCP工具 6 12
最大节省 60% 85%
字符串字典 ❌ ✅
值压缩 ❌ ✅
部分架构 ❌ ✅
zlib支持 ❌ ✅
AI分析 基础 高级
自定义缩写 ❌ ✅
节省估算 ❌ ✅

🤝 贡献

欢迎投稿!拜托:

  1. 分叉存储库
  2. 创建要素分支(git checkout -b feature/amazing-feature)
  3. 运行测试(pytest tests/ -v)
  4. 格式代码(black src/ tests/)
  5. 提交更改(git commit -m 'Add amazing feature')
  6. 推送到分支(git push origin feature/amazing-feature)
  7. 打开拉取请求

🌟 用例

1. 大型API响应

在Claude对话中存储API响应时,可节省50-65%的令牌。

2. 数据库查询结果

将数据库结果压缩60-70%,以实现高效的上下文使用。

3. 时间序列数据

在时态数据集上实现65-75%的压缩。

4. 配置文件

以紧凑的格式存储配置,节省40-55%。

5. 代码库分析

在分析代码时,在令牌限制中容纳更多文件内容。

6. 日志处理

将结构化日志压缩50-60%以进行模式分析。


🚦 快速提示

何时使用每个级别

  • 最小:快速转换,需要高速
  • 标准:通用(最佳平衡)
  • 激进的:大型数据集,需要大量节省
  • 极端:最大程度的压缩,存档使用

优化配置文件

  • 速度:首选最低/标准级别
  • 平衡的:根据数据自动选择(推荐)
  • 尺寸:更倾向于激进/极端级别

最佳实践

  1. ✅ 首先分析模式 analyze_patterns
  2. ✅ 使用 smart_optimize 自动获得最佳结果
  3. ✅ 验证方式 validate_toon 转换后
  4. ✅ 使用 estimate_savings 在大批量作业之前
  5. ✅ 监视器 get_server_stats 用于度量
pip install -e .
python -m src.mcp_server