Files
NebulaShell/store/@{FutureOSS}/json-codec
qwen.ai[bot] d7978349ed Title: Update license confirmation and enhance project documentation
Key features implemented:
- Updated README.md to prominently display MIT license badge and include full license text in expandable section
- Enhanced .gitignore with comprehensive file patterns for Python, dependencies, logs, and build artifacts
- Added detailed plugin manifest example showing license declaration in plugin configuration
- Included license information in plugin development documentation section

The updates provide clear license visibility and improved development workflow configuration.
2026-04-25 08:14:10 +00:00
..
2026-04-17 23:15:15 +08:00
2026-04-17 23:15:15 +08:00

json-codec JSON 编解码器

提供插件间 JSON 数据的编码、解码和验证功能。

功能

  • JSON 编码: Python 对象 → JSON 字符串
  • JSON 解码: JSON 字符串 → Python 对象
  • Schema 验证: 验证 JSON 数据结构
  • 自定义类型: 支持注册自定义类型编解码器

基本使用

codec = plugin_mgr.get("json-codec")

# 编码
data = {"name": "test", "count": 42}
json_str = codec.encode(data)
# '{"name": "test", "count": 42}'

# 编码(格式化)
json_pretty = codec.encode(data, pretty=True)
# '{\n  "name": "test",\n  "count": 42\n}'

# 解码
parsed = codec.decode(json_str)
# {"name": "test", "count": 42}

HTTP 响应处理

# 在 http-api 插件中使用
router.get("/api/users", lambda req: Response(
    status=200,
    headers={"Content-Type": "application/json"},
    body=codec.encode({"users": [...]})
))

Schema 验证

# 注册 schema
codec.register_schema("user", {
    "type": "object",
    "required": ["name", "email"],
    "properties": {
        "name": {"type": "string"},
        "email": {"type": "string"},
        "age": {"type": "number"}
    }
})

# 验证数据
user_data = {"name": "test", "email": "test@example.com"}
is_valid = codec.validate(user_data, "user")

自定义类型

from datetime import datetime

# 注册自定义编码器
codec.serializer.register_encoder(datetime, lambda dt: dt.isoformat())

# 使用
data = {"created_at": datetime.now()}
json_str = codec.encode(data)

错误处理

from oss.plugin.types import JsonCodecError

try:
    result = codec.decode("invalid json")
except JsonCodecError as e:
    print(f"解码失败: {e}")