Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions AXXZSTHL/json-to-toon-plugin/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# Virtual Environment
venv/
ENV/
env/

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# OS
.DS_Store
Thumbs.db

# Dify Plugin
*.pkg

47 changes: 47 additions & 0 deletions AXXZSTHL/json-to-toon-plugin/PRIVACY_POLICY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# 隐私政策

## JSON to TOON Converter 插件隐私政策

**最后更新日期:** 2025年

### 数据收集

JSON to TOON Converter 插件(以下简称"本插件")**不会收集、存储或传输任何用户数据**。

### 数据处理

1. **本地处理**:所有 JSON 到 TOON 的转换操作都在用户本地环境或 Dify 平台内完成
2. **无外部传输**:转换过程中不会将数据发送到任何外部服务器或第三方服务
3. **无数据存储**:插件不会存储用户的输入数据或转换结果

### 数据安全

- 所有数据处理都在安全的本地环境中进行
- 不涉及任何网络传输或外部 API 调用
- 用户数据完全由用户控制

### 第三方服务

本插件不依赖任何第三方服务,不涉及任何外部 API 调用。

### 用户权利

用户对其数据拥有完全的控制权:
- 数据不会被收集或存储
- 数据不会被共享或出售
- 用户可以随时停止使用本插件

### 政策变更

如果我们对隐私政策进行任何更改,我们将在本页面发布更新后的隐私政策。

### 联系我们

如果您对本隐私政策有任何疑问,请通过以下方式联系我们:
- GitHub Issues: [https://github.com/AXXZSTHL/json-to-toon-plugin]
- Email: 528360026@qq.com

---

**重要提示**:本插件是一个纯本地处理工具,不会访问互联网或存储任何数据。您的数据隐私和安全是我们的首要考虑。

124 changes: 124 additions & 0 deletions AXXZSTHL/json-to-toon-plugin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# JSON to TOON Converter Plugin

## 简介

JSON to TOON Converter 是一个 Dify 插件,用于将 JSON 内容转换为 TOON(Token-Oriented Object Notation)格式,从而大幅降低 token 使用量。

TOON 格式通过移除 JSON 中的冗余符号(如大括号、中括号和引号),同时保持数据结构的清晰度,可以平均减少 30-60% 的 token 消耗。

## 功能特性

- ✅ 将 JSON 数据转换为 TOON 格式
- ✅ 支持嵌套对象和数组
- ✅ 保持数据结构清晰可读
- ✅ 显著减少 token 使用量(平均 30-60%)
- ✅ 错误处理和验证

## 安装

1. 在 Dify 插件市场中搜索 "JSON to TOON Converter"
2. 点击安装按钮
3. 插件将自动配置并可用

## 使用方法

### 在 Dify 工作流中使用

1. 在工作流中添加 "JSON to TOON Converter" 工具节点
2. 将需要转换的 JSON 内容作为输入
3. 工具将返回 TOON 格式的字符串

### API 调用示例

```python
import requests

url = "http://your-dify-instance/api/plugins/json_to_toon/convert"
payload = {
"json_content": '{"users": [{"id": 1, "name": "Alice", "role": "admin"}, {"id": 2, "name": "Bob", "role": "user"}]}'
}

response = requests.post(url, json=payload)
print(response.text)
```

### 输入示例

**JSON 输入:**
```json
{
"users": [
{"id": 1, "name": "Alice", "role": "admin"},
{"id": 2, "name": "Bob", "role": "user"}
],
"settings": {
"theme": "dark",
"notifications": true
}
}
```

**TOON 输出:**
```
users[2]{id,name,role}:
1,Alice,admin
2,Bob,user
settings:
theme: dark
notifications: true
```

## TOON 格式说明

TOON 格式的特点:

1. **数组表示**:`key[length]{columns}:` 表示数组,其中 `length` 是数组长度,`columns` 是对象数组的键名
2. **对象表示**:使用缩进表示嵌套关系
3. **值表示**:`key: value` 格式表示键值对
4. **无冗余符号**:移除了 JSON 中的 `{}`, `[]`, `"` 等符号

## 配置

本插件无需额外配置,安装后即可使用。

## 隐私政策

本插件不会收集、存储或传输任何用户数据。所有数据处理都在本地完成,不会发送到外部服务器。

详细的隐私政策请参阅 [PRIVACY_POLICY.md](./PRIVACY_POLICY.md)

## 开发

### 本地开发

1. 克隆仓库
2. 安装依赖:
```bash
pip install -r requirements.txt
```
3. 运行服务:
```bash
python app.py
```
4. 测试 API:
```bash
curl -X POST http://localhost:5001/convert \
-H "Content-Type: application/json" \
-d '{"json_content": "{\"test\": \"value\"}"}'
```

## 许可证

MIT License

## 支持

如有问题或建议,请提交 Issue 或 Pull Request。

## 更新日志

### v1.0.0
- 初始版本发布
- 支持 JSON 到 TOON 格式转换
- 支持嵌套对象和数组

170 changes: 170 additions & 0 deletions AXXZSTHL/json-to-toon-plugin/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
"""
JSON to TOON Converter Plugin for Dify
Converts JSON content to TOON (Token-Oriented Object Notation) format
to significantly reduce token usage in LLM interactions.
"""

import json
from typing import Any, Dict, List, Union
from flask import Flask, request, jsonify

app = Flask(__name__)


def json_to_toon(data: Any, indent: int = 0) -> str:
"""
Convert JSON data to TOON format.

TOON (Token-Oriented Object Notation) removes redundant symbols
like braces, brackets, and quotes while maintaining structure clarity.

Args:
data: The data to convert (dict, list, or primitive)
indent: Current indentation level

Returns:
TOON formatted string
"""
indent_str = " " * indent

if isinstance(data, dict):
if not data:
return "{}"

lines = []
for key, value in data.items():
if isinstance(value, (dict, list)) and value:
if isinstance(value, list):
# Handle list of objects
if value and isinstance(value[0], dict):
# Check if all items are simple objects (no nested complex types)
all_simple = all(
isinstance(item, dict) and
not any(isinstance(v, (dict, list)) for v in item.values())
for item in value
)

if all_simple:
# Extract keys from first object
keys = list(value[0].keys())
lines.append(f"{indent_str}{key}[{len(value)}]{{{','.join(keys)}}}:")
for item in value:
if isinstance(item, dict):
values = [str(item.get(k, "")) for k in keys]
lines.append(f"{indent_str} {','.join(values)}")
else:
lines.append(f"{indent_str} {item}")
else:
# Complex nested structures - use nested format
lines.append(f"{indent_str}{key}[{len(value)}]:")
for item in value:
item_str = json_to_toon(item, indent + 1)
for line in item_str.split('\n'):
if line.strip():
lines.append(line)
else:
# Simple list
lines.append(f"{indent_str}{key}[{len(value)}]:")
for item in value:
item_str = json_to_toon(item, indent + 1)
lines.append(f"{indent_str} {item_str}")
else:
# Nested dict
lines.append(f"{indent_str}{key}:")
nested = json_to_toon(value, indent + 1)
for line in nested.split('\n'):
if line.strip():
lines.append(line)
else:
# Primitive value
value_str = str(value) if value is not None else "null"
lines.append(f"{indent_str}{key}: {value_str}")

return '\n'.join(lines)

elif isinstance(data, list):
if not data:
return "[]"

lines = []
# Check if it's a list of objects
if data and isinstance(data[0], dict):
keys = list(data[0].keys())
lines.append(f"{indent_str}[{len(data)}]{{{','.join(keys)}}}:")
for item in data:
if isinstance(item, dict):
values = [str(item.get(k, "")) for k in keys]
lines.append(f"{indent_str} {','.join(values)}")
else:
lines.append(f"{indent_str} {json_to_toon(item, indent + 1)}")
else:
# Simple list
for item in data:
item_str = json_to_toon(item, indent)
lines.append(f"{indent_str}{item_str}")

return '\n'.join(lines)

else:
# Primitive value
if data is None:
return "null"
elif isinstance(data, bool):
return str(data).lower()
elif isinstance(data, (int, float)):
return str(data)
else:
return str(data)


@app.route('/health', methods=['GET'])
def health():
"""Health check endpoint"""
return jsonify({"status": "healthy"}), 200


@app.route('/convert', methods=['POST'])
def convert():
"""
Convert JSON content to TOON format.

Request body:
{
"json_content": "string" # JSON string to convert
}

Returns:
TOON formatted string
"""
try:
request_data = request.get_json()

if not request_data:
return jsonify({"error": "Request body is required"}), 400

json_content = request_data.get('json_content')

if json_content is None:
return jsonify({"error": "json_content field is required"}), 400

# Parse JSON string
try:
if isinstance(json_content, str):
data = json.loads(json_content)
else:
data = json_content
except json.JSONDecodeError as e:
return jsonify({"error": f"Invalid JSON format: {str(e)}"}), 400

# Convert to TOON
toon_output = json_to_toon(data)

return toon_output, 200, {'Content-Type': 'text/plain; charset=utf-8'}

except Exception as e:
return jsonify({"error": f"Internal server error: {str(e)}"}), 500


if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001, debug=False)

Loading
Loading